从firebase声明全局变量的最佳方式



我想从firebase:中声明一个全局对象

我的代码如下:

app.component.ts

export class AthleticsApp {
af.auth.subscribe(user => {
// here i want to make the user global somehow
});

有可能让用户全球化吗?最好或最简单的方法是什么?

非常感谢!

如果您真正需要做的只是为组件提供一个全局对象,请考虑使用不透明的令牌。

然而,由于对象也必须被解析——理想情况下只解析一次——我会考虑将其嵌入一个小型服务中,作为firebase的门面:

@Injectable()
export class UserService {
private _user;
public get user(): Observable<User> {
if (!this._user) {
this._user = this.af.auth.cache();  // .cache guarantees at most one request
}
return this._user;
}
private af;
constructor() {
...establish af reference
}
}

通过将此服务添加为AppComponent级别的提供程序,可以使其对所有组件都可用:

@Component({
selector: 'my-app',
template: '<my-comp></my-comp>'
providers: [
UserService
]
})
export class AppComponent { 
}

需要用户对象的组件可以通过服务访问它。请注意,用户将仅被解析一次,这是由服务中的.cache操作员提供的。

@Component({
selector: 'my-comp',
template: '...'
})
export class MyComp { 
constructor(private userService: UserService) {
this.userService.user.subscribe(user => {
...deal with the user
});
}
}

如果你真的想摆脱userService.user.subscribe(尽管它会立即返回所有后续请求),你可以在第一次使用之前使用路由解析程序来解析对象

编辑:可能需要强调的是,您通过将UserService的同一实例添加为AppComponent级别的提供程序,在所有组件中传递该实例,因此它充当全局可用变量。这是一个非常强大的特性,专门用于角2依赖项注入。

假设您有两个类:

var MyVariable = ' ';
export class AthleticsApp1 {
af.auth.subscribe(user => {
// MyVariable is accessible here
});
export class AthleticsApp2 {
af.auth.subscribe(user => {
// MyVariable is accessible here
});

现在,MyVariable可以由这两个类访问,而不会出现任何问题,因为它属于作用域。

如果firebase会随着时间的推移更新用户对象,我建议使用Redux并将该用户对象放入状态树中。

这种sulotion将只产生一个对象,其他组件将同时使用该对象,并且每个组件将从firebase获得更新最多的对象。

Ngrx/商店(Angular2的Redux):https://github.com/ngrx/store

然后更改:

af.auth.subscribe(user => {
your_redux_store_object.dispach({action: Actions.USER_UPDATE,payload: user});
});

随着时间的推移,每个组件将使用同一存储对象的更新。

最新更新