Angular2 - 在多个组件'手表'Provider属性 [英] Angular2 - 'watch' provider property in multiple components

查看:216
本文介绍了Angular2 - 在多个组件'手表'Provider属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来了形式NG1环境和我目前正在创建NG2应用所有可用的功能。问我正在探索谷歌和计算器的问题,但没有运气,因为角2移动如此之快与API架构和最答案之前已经过时了。

I'm coming form NG1 environment and currently I'm creating NG2 app with all available features. Before asking I was exploring google and stackoverflow questions but with no luck since angular 2 moved so fast with api architecture and most answers are out of date.

我的情况:
我有验证提供商(服务)财产用户,我想观察的用户,并在多个组件发生反应(导航栏,侧边栏等等。)

My case: I have Auth provider (service) with property user, I would like to observe user and react in multiple components (navbar, sidebar etc.)

我试过:

@Injectable();
export class Auth {

    private user;
    authorized: EventEmitter<boolean>;

    constructor(public router:Router){
        this.authorized = new EventEmitter<boolean>();
    }

    login(user, token):void{
        localStorage.setItem('jwt', token);
        this.user = _.assign(user);

        this.authorized.emit(<boolean>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
])

但没有运气。我应该用观测EventEmitter或者有处理这种情况其他正确的做法?在NG1这将是作为服务的属性设置$手表一样简单。谢谢!

But with no luck. Should I use Observable EventEmitter or maybe there is other correct approach to handle this case? In NG1 it would be as simple as set $watch on service's property. Thanks!

编辑:
我增加了新的方法来验证服务:

I added new method to Auth service:

...
userUpdated: EventEmitter<boolean>;

constructor(public router:Router){
    this.userUpdated = new EventEmitter<any>();
}

...

logout(returnUrl?: string): void{
    delete this.user;
    localStorage.removeItem('jwt');
    this.userUpdated.emit(undefined);

    if(!_.isEmpty(returnUrl)){
        this.router.parent.navigateByUrl(returnUrl);
    }

}

现在事件被称为,这是为什么工作注销而不是登录?

And now event is called, why is this working for logout and not for login?

编辑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);
   }

}

议决

愚蠢的错误..我留在NavComponent在供应商数组[验证] ..所以这是不同的对象不是全局验证..对不起你们!希望这个问题将有助于新的人选在Angular2。感谢你的努力。

Silly mistake.. i left in NavComponent in providers array [Auth].. so it was different object than global Auth.. sorry guys! Hope this issue will help somebody new in Angular2. Thanks for your effort.

推荐答案

我假设你要添加验证作为供应商的所有组件。这个创建类为各成分的新实例。
添加它只能在引导(AppComponent,供应商:[...])。或仅在 AppComponent

I assume you are adding Auth as provider to every component. This creates a new instance of the class for each component. Add it only in bootstrap(AppComponent, providers: [...]) or only on the AppComponent.

这篇关于Angular2 - 在多个组件'手表'Provider属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆