我来自NG1环境,目前我正在创建具有所有可用功能的NG2应用程序.在问我之前我正在探索google和stackoverflow问题,但没有运气,因为angular 2移动得如此之快,api架构和大多数答案都已过时.
我的情况:我有属性用户的Auth提供者(服务),我想观察用户并对多个组件做出反应(导航栏,侧栏等)
我尝试了什么:
@Injectable(); export class Auth { private user; authorized: EventEmitter; constructor(public router:Router){ this.authorized = new EventEmitter (); } login(user, token):void{ localStorage.setItem('jwt', token); this.user = _.assign(user); this.authorized.emit( true); this.router.parent.navigateByUrl('/'); } } /***************/ @Component({...}) export class NavComponent { public isAuthroized: boolean = false; constructor(Auth:Auth){ Auth.authorized .subscribe((data) => this.onUserChanged(data)); } onUserChanged(user){ alert('USER:' + user.email); this.isAuthroized = true; } } /****************/ bootstrap(AppComponent, [ ROUTER_PROVIDERS, ELEMENT_PROBE_PROVIDERS, HTTP_PROVIDERS, MapLoader, Auth ])
但没有运气.我应该使用Observable EventEmitter还是有其他正确的方法来处理这种情况?在NG1中,它就像在服务的属性上设置$ watch一样简单.谢谢!
编辑:我为Auth服务添加了新方法:
... userUpdated: EventEmitter; constructor(public router:Router){ this.userUpdated = new EventEmitter (); } ... logout(returnUrl?: string): void{ delete this.user; localStorage.removeItem('jwt'); this.userUpdated.emit(undefined); if(!_.isEmpty(returnUrl)){ this.router.parent.navigateByUrl(returnUrl); } }
现在调用事件,为什么这适用于注销而不是登录?
编辑2:
export class LoginPageComponent { error: string; constructor(public http: Http, public router: Router, public Auth:Auth){ } login(event, email, password){ ... this.http.post('/api/login', loginModel, {headers: headers}) .map((res) => res.json()) .subscribe((res: any) => { this.Auth.login(res.user, res.ADM_TOKEN); }, (error) => this.error = error._body); } }
解决
愚蠢的错误..我离开了提供者数组[Auth]中的NavComponent ..所以这是与全球Auth不同的对象..抱歉伙计们!希望这个问题能帮助Angular2中的新人.谢谢你的努力.