在我的angular应用程序中,我有一个父组件,即Dashboard组件,有两个子组件,即Analytics组件和Stats组件。我的
dashboard.component.html
看起来像这样
<div class="row">
<div class="col-lg-6"><app-analytics></app-analytics></div>
<div class="col-lg-6"><app-stats></app-stats></div>
</div>
我还使用了一个全局组件,它对所有组件都可用,就像一个全局存储一样。现在在
dashboard.component.ts
. 我正在对服务器进行HTTP调用,获取数据并将其保存到全局组件中。
仪表板.component.ts
import { Component, OnInit } from '@angular/core';
import { Global } from 'app/shared/global';
import { Http } from '@angular/http';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
constructor(private http : Http){
};
ngOnInit(){
this.http.get('/api/getUserPreferences').subscribe(response=>{
var data = response.json();
Global.userPreferences = data.preferences;
})
}
我在子组件(即分析组件和统计组件)中使用的用户首选项。
分析.component.ts
import { Component, OnInit } from '@angular/core';
import { Global } from 'app/shared/global';
import { Http } from '@angular/http';
@Component({
selector: 'app-analytics',
templateUrl: './analytics.component.html',
styleUrls: ['./analytics.component.css']
})
export class AnalyticsComponent implements OnInit {
public analyticsUserPreferences : any;
constructor(private http : Http){
};
ngOnInit(){
this.analyticsUserPreferences = Global.userPreferences.analytics;
// Printing just for the question purpose
console.log(this.analyticsUserPreferences);
}
}
统计组件ts
import { Component, OnInit } from '@angular/core';
import { Global } from 'app/shared/global';
import { Http } from '@angular/http';
@Component({
selector: 'app-stats',
templateUrl: './stats.component.html',
styleUrls: ['./stats.component.css']
})
export class StatsComponent implements OnInit {
public statsUserPreferences : any;
constructor(private http : Http){
};
ngOnInit(){
this.statsUserPreferences = Global.userPreferences.stats;
// Printing just for the question purpose
console.log(this.statsUserPreferences);
}
}
undefined
每次在控制台里。有什么办法可以等到
Global.userPreferences
不包含值。或者有没有其他方法可以做到这一点。我只希望它应该等到http请求完成,并在值存储在
全局.userPreferences
.