我使用这种方法进行绑定,但是当我重新加载页面时,它的工作停止
<div><h1>{{userdata?.firstname}}</h1></div>
export class HomeComponent {
constructor(private authenticationService : AuthenticationService) {
userdata=this.authenticationService.user_data;
}
}
您的服务可能看起来像这样......
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable()
export class AuthenticationService {
private _user_data: BehaviorSubject<any> = new BehaviorSubject<any>(null);
constructor() {
this._restoreUser()
}
get user_data(): Observable<any> {
return this._user_data.asObservable();
}
private _restoreUser(): void {
let user: any;
// use any code to restore user from cache and assign it to the scoped user variable
this._user_data.next(user);
}
}
在您的家庭组件中...
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
export class HomeComponent implements OnInit, OnDestroy {
public userdata: any;
private _userdataSub: Subscription;
constructor(private authenticationService: AuthenticationService) { }
ngOnInit() {
this._userdataSub = this.authenticationService.user_data.subscribe((userdata) => {
this.userdata = userdata;
});
}
ngOnDestroy() {
this._userdataSub.unsubscribe();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句