我想聲明的火力點一個全局對象:從firebase聲明全局變量的最佳方式是什麼?
我的代碼如下所示:
app.component.ts
export class AthleticsApp {
af.auth.subscribe(user => {
// here i want to make the user global somehow
});
是有可能使用戶的全球?什麼是最好的或最簡單的方法呢?
非常感謝!
我想聲明的火力點一個全局對象:從firebase聲明全局變量的最佳方式是什麼?
我的代碼如下所示:
app.component.ts
export class AthleticsApp {
af.auth.subscribe(user => {
// here i want to make the user global somehow
});
是有可能使用戶的全球?什麼是最好的或最簡單的方法呢?
非常感謝!
假設您有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的訪問是由兩個類沒有任何問題的原因是該範圍之內下降。
如果您真的需要做的是爲您的組件提供全局對象,請考慮opaque token。
然而,由於對象必須得到解決,以及 - 甚至是隻有一次 - 我會考慮在充當門面小服務嵌入這對火力點:
@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(儘管它會立即返回所有後續請求),你可以提前一次使用的使用route resolver
編輯解析對象:可能需要強調的是,您將通過在AppComponent級別將其作爲提供者添加到所有組件中的UserService的相同實例 - 因此它充當全局可用變量。這是angular 2 dependency injection特有的非常強大的功能。
隨着時間的推移更新您的用戶對象的火力基地,我會建議使用Redux並將該用戶對象放在狀態樹內。
這個推理只會導致一個對象,每個其他compoents將同時使用,每個組件將從firebase獲取最新的對象。
NGRX /存儲(終極版爲Angular2):https://github.com/ngrx/store
然後改變:
af.auth.subscribe(user => {
your_redux_store_object.dispach({action: Actions.USER_UPDATE,payload: user});
});
每個compoenent將用相同的存儲對象消耗隨時間更新。
在類之外聲明一個變量,即在它之前聲明'var MyVariable =''; –
當然,這對於一個類是有效的。但是,如果我想在另一個班級中使用全局,它不再工作了: 「錯誤在.... class TabsPage - 由:GLOBAL_USER未定義」 – Fargho
實際上它不適用於一個類。如果您在頂部書寫(讓我們假設),那麼所有類都可以訪問該全局變量。在這種情況下,它將在所有範圍內均等提供。請嘗試一次。我正在將其作爲答案。如果它幫助你,那麼請upvote /接受它:) –