Observables return type

Issue

I’m sending my request to the API and parsing it with the map function:

//part of service
post(url: string, params): Observable<Response> {
    let requestUrl: string = this.apiUrl + url;
    return this.http.post(requestUrl, params)
        .map(response => response.json());
}
    
//part of other service
doLogin(login, haslo): Observable<Response> {
    return this.apiService.post('auth/login/', {login: login, haslo: haslo});
}

As a result I get a boolean value and use it in subscribe function:

this.authService.doLogin(this.model.login, this.model.haslo)
    .subscribe(result => {
        //result is boolean - not Response
        this.authService.loggedIn = result;
        this.result = result
    });

The problem is that in doLogin‘s subscriber, TypeScript says that result is Response instead of boolean – how do I fix this?

Solution

That’s cause of your function prototypes:

post(url: string, params): Observable<Response>

doLogin(login, haslo): Observable<Response>

They should be:

Observable<boolean>

Do it like this:

//part of service
post(url: string, params): Observable<any> {
    let requestUrl: string = this.apiUrl + url;
    return this.http.post(requestUrl, params)
        .map(response => response.json());
}

//part of other service
doLogin(login, haslo): Observable<boolean> {
    return this.apiService.post('auth/login/', {login: login, haslo: haslo})
       .map(result => result == true /* or any check here and return an BOOLEAN !!*/);
}

Answered By – slaesh

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.