wie Sie Sie abonnieren, um eine beobachtbare in einen anderen Dienst im Winkel 2
Ich habe einen service, der einfach sagt, wenn ein Benutzer angemeldet ist oder nicht.
Es wird aktualisiert von einem anderen Dienst, die die http-Anforderung, um zu überprüfen, der Nutzer.
Möchte ich ein nav-bar-Komponente für die Aktualisierung der Benutzeroberfläche, um dem Benutzer ein login-oder logout-button auf der Grundlage der beobachtbaren (BehaviorSubject) .
(in meiner bootstrap-Funktion ich bin Injektion Auth)
nav-main.Komponente.ts
import {Auth} from '../services/auth.service';
constructor ( public _auth: Auth) {
this._auth.check().subscribe(data =>{console.log(data)})
}
auth.service.ts
@Injectable()
export class Auth {
subject: Subject<boolean> = new BehaviorSubject<boolean>(null);
loggedIn:boolean = false;
constructor(){
this.subject.next(this.loggedIn);
}
login(id_token){
...
this.loggedIn = true;
this.subject.next(this.loggedIn);
}
check() {
return this.subject.asObservable().startWith(this.loggedIn);
}
}
login.service.ts
import {Injectable, Injector} from 'angular2/core';
import {Http,Headers} from 'angular2/http';
import {AppInjectorService} from './app-injector.service';
import {Auth} from './auth.service';
import {UserService} from './user.service'
import 'rxjs/Rx';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class LogInUserService {
auth:Auth;
injector:Injector;
constructor(private http:Http) {
//let injector: Injector= AppInjectorService();
this.injector = Injector.resolveAndCreate([Auth]);
this.auth = this.injector.get(Auth);
}
logInUser(data) {
...
return this.http.post(this._authUrl, body, { headers:headers})
.map(function(res){ return <UserService> res.json().data;})
.do(data => this.logIn(data))
.catch(this.handleError);
}
//on success tell the auth.login the public key
logIn(data){
this.auth.login(data.publicKey);
}
InformationsquelleAutor Randy Collier | 2016-05-19
Du musst angemeldet sein, um einen Kommentar abzugeben.
@Inject(Auth) _auth geschaut haben getan der trick.
nav-main.Komponente.ts
auth.service.ts
InformationsquelleAutor Randy Collier