当数据可用时,Angular2组件不会更新

时间:2017-03-12 06:58:00

标签: angular angular2-services angular2-components angular2-observables

我有一个组件,其属性绑定到数据属性。

@Component({
 encapsulation: ViewEncapsulation.None,
 selector: 'animal-detail-main',
 styleUrls: ['animal-detail-main.component.scss'],
 template: `
      <div>
        {{data | json}}
      </div>
      `
})

export class DetailMain  {
  data: any;

 private dataSvc: MainService;

 constructor( 
    @Inject(MainService)  dataSvc: MainService,
    ) {
      this.dataSvc = dataSvc;
    }

  ngOnInit() {
        var fetchedData: any;

        this.dataSvc.currentID$
           .subscribe(
              currentID => {
                   currentID = currentID;
                   this.dataSvc
                     .getDetail(currentID)
                     .map(response => response.json())
                     .subscribe (
                         data => {fetchedData = data[0]},
                          err => console.log('Error',err),
                          () => {
                          console.log('fetchedData',fetchedData);
                          setTimeout(() => {
                             this.data = fetchedData;
                             console.log("this.data",this.data);
                          }, 2000);
                    }
           );
      });   
 }
}

基本上,currentID $服务保存当前对象的ID,以便将其提取回currentID,然后将currentID传递给getDetail服务以返回该ID的整个对象。

如果没有setTimeout,该函数会延迟返回对象数据,并且永远不会将其分配给this.data。

使用setTimeout,在this.data之后的console.log被分配fetchData返回对象正确地记录返回的对象,但视图永远不会更新,因此数据不会显示在组件中。

我预计一旦数据可用,该组件会自动刷新,但它没有,我也不知道如何触发视图更新。

1 个答案:

答案 0 :(得分:1)

我认为您可能希望在此处使用flatMap来链接请求,因为第二个请求取决于您的服务中的Observable。编辑。如果您的ID为BehaviorSubject,则效果很好。

constructor(private dataSvc: MainService) { }

data: any = {}; // if it's an object

ngOnInit() {
   this.dataSvc.currentID$
     .flatMap(currentId => this.dataSvc.getDetail(currentId))
        .map(res => res.json()) // could do the mapping in the service
        .subscribe(data => {
           this.data = data[0];
        });
}

关于视图未更新,不完全确定....尝试上述解决方案,如果模板未更新,您可以尝试使用ChangeDetectorRef手动触发更改检测,但我不知道真的明白为什么变化检测不会发生。但这些事情似乎有时会发生:)