Trevor Hector
Trevor Hector

Reputation: 639

Angular 2 observe result of http

Here I have a Service. Its signIn method will fire a method of another Service which returns an Observable. Every component should be able to subscribe to the result of that Observable. So I created a public response variable as Observable, which can be accessed from every component. I don't think I can directly subscribe to signIn because it requires two parameters which only one Observer would actually know.

The problem is that response is undefined at the beginning. So you can't subscribe to it in a constructor of another component.

So how can I subscribe to response when I don't know when the data will arrive? Any ideas?

export class AuthService{

    public response:Observable<any[]>;

    constructor(private httpService:HTTPService){
        this.response = new Observable();
    }

    signIn(user:String, password:String){

        this.response = this.httpService.query({user: user, pass: password})
        .map((r: Response) => r.json());

    }
}

This is the AuthComponent method where user and password come from

onSubmit(f:NgForm){
    this.authService.signIn(f.value.user, f.value.password);
}

Upvotes: 2

Views: 1211

Answers (1)

slaesh
slaesh

Reputation: 16917

Normally you should just return that Observable:

import { BehaviorSubject } from 'rxjs';

export class AuthService {

    public data = new BehaviorSubject<any[]>([]);

    constructor(private httpService: HTTPService) { }

    signIn(user:String, password:String): Observable<any[]> {

        return this.httpService.query({user: user, pass: password})
           .map((r: Response) => r.json())
           .map(data => { this.data.next(data); return data; }); // OPTIONAL if you want to store data in you service..

    }
}

Other components can now subscribe to that data subject.

The calling component will subscribe and its done.

Http-Request-Observables are completed after each request.

Upvotes: 2

Related Questions