等到请求在 angular 内完成

wait till the request completes in angular

在我的 angular 应用程序中,我有一个父组件,即具有 2 个子组件的仪表板组件,即分析组件和统计组件。我的 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 调用,获取数据并将其保存到全局组件中。

dashboard.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;
  })
}

我在子组件(即分析组件和统计组件)中使用的用户首选项。

analytics.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);
 }
}

stats.component.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 请求完成并在值存储在 Global.userPreferences.

中时打印

您可以使用异步管道和 *ngIf 来等待 http 请求完成,然后再呈现子组件。然后使用绑定将数据向下传递给子组件并使用@Input() 接收它。

dashboard.component.ts

public userPreferences$: Observable<any>;

ngOnInit(){
  this.userPreferences$ = this.http.get('/api/getUserPreferences').subscribe();
  })

dashboard.html

<app-analytics *ngIf="userPreferences$ | async as userPreferences" [userPreferences]="userPreferences"></app-analytics>