Search code examples
angularobservableresolver

How can resolve some stuff/ajax call before to display my view in Angular 2?


I've already tried this suggestion, but it doesn't work Observable doest have any "fromPromise" method and typescript rises up an error.

import {Observable} from "rxjs/Rx";
import {Http} from "@angular/http";
import {GLOBAL_CONST} from "../global-const";
import {Resolve, ActivatedRouteSnapshot, RouterStateSnapshot} from "@angular/router";

export class ResolverSignupBegin{//} implements Resolve<any>{

    signupBeginData:any[];

    constructor(private http:Http){}

    getData(){
        return this.http.get(GLOBAL_CONST.apiPath + "/user/login/api-logged-in")
            .map(res => res.json())
            .subscribe(
                (data) => { console.log("data", data); return data; },
                (err) => { console.log("error", err); }
            );
    }


    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<any>{
        return this.getData();
    }


}

I havean error on "this".getData saying that " Error:(28, 16) TS2322: Type 'Subscription' is not assignable to type 'Observable'. Property '_isScalar' is missing in type 'Subscription'. "


Solution

  • If you subscribe you get a Subscription but resolve needs to return an Observable.

    Instead of subscribing yourself return an observable and let Angular do the subscription

    getData(){
        return this.http.get(GLOBAL_CONST.apiPath + "/user/login/api-logged-in")
            .map(res => res.json())
            .catch((err) => { console.log("error", err); throw err;}
            .do(
                (data) => { console.log("data", data)},
            );
    }
    

    Don't forget that you need to import operators like map and do. See Angular 2 HTTP GET with TypeScript error http.get(...).map is not a function in [null]