Angular 2 Observable Refresh

时间:2017-02-15 14:55:13

标签: angular

我试图在子组件更新操作后刷新父表。

@服务

getLicenses(){
     ...
     return this.http.post(url","",options)
        .map((result: Response) => result.json())
          .map((data: License[]) => {
              this.licenses = data;

              return this.licenses;
            })
            .catch(this.handleError);
}

@ parent component

 ngOnInit() {
    this.licenseService.getLicenses().subscribe(licenses => {
                                          this.licenses = licenses;
 }); 

一切看起来都很擅长初始化。我在表中有数据。 当从表中选择一行时,我将它传递给子组件并执行更新操作。更新后,我想刷新表并调用getLicenses()方法的服务。但它没有刷新。如果我调用另一种方法进行测试,它会刷新我的表。

  getLicenses2(){
    this.licenses.pop();
    this.licenses.pop();
    this.licenses[2].isFree=  !this.licenses[2].isFree;
  }

此外,我测试如下,这不会刷新。

  getLicenses2(){

       this.http.post(url,"",options)
            .map((result: Response) => result.json())
              .map((data: License[]) => {
                  this.licenses = data;
                  this.licenses.pop();
                  this.licenses.pop();
                })
                .catch(this.handleError);
  }

为什么在手动更改阵列时这会起作用? 当我分配json数据时为什么不起作用?

我的回答没问题,没有异常,第一次初始化效果很好。如果我只是用f5新数据刷新表,那么更新操作也是成功的。 (我是Angular 2的新手)

修改

如果我只是更改数组,它可以使用或不使用主题但是当我在http post

中执行它时它不起作用

我尝试过使用主题。这次没有孩子。当我调用http post时,初始化不起作用。见下面的测试方法。

@service我有

private licenses2 = new Subject<License[]>();
licenses2$ = this.licenses2.asObservable();

@ parent component

 ngOnInit() {
    this.licenseService.licenses2$.subscribe(licenses => {
        this.licenses = licenses;
     } );
    this.licenseService.getLicenses2();
 }

作品

getLicenses2() {
   let test: License[] = [];
   test.push(new License());

   this.licenses2.next(test)
}

不起作用

 getLicenses2(){
   this.http.post(URL,"",options)
        .map(response => {
              this.licenses2.next(response.json() as License[])
        })
        .catch(this.handleError);
  }

谢谢。

1 个答案:

答案 0 :(得分:2)

一种解决方案是使用Subject。根据我从您的评论中理解的内容,您正在尝试从子项更新父表,这将无效,因为更新仅在子项中出现(如果您这样做)。所以你可以做的是告诉父母在你需要的时候更新数据。请尝试以下方法:

在父母中声明主题:

public static updateStuff: Subject<any> = new Subject();

并在您的父构造函数中订阅:

ParentComponent.updateStuff.subscribe(res => {
    // here fire functions that fetch the data from the api
    this.getLicenses(); // add this!
})

并且在您的子组件中,每当您进行应在父项中更新的更改时,请执行以下操作:

ParentComponent.updateStuff.next(false);

例如,在您的孩子做完邮寄请求后:

// this is the method you call in your child component to do the post request
postChanges() { 
  this.myService.updateTable()
     .subscribe(data => {
        this.data = data;
        ParentComponent.updateStuff.next(false); // add this, will update the parent!
  })
}

...然后它应该工作:)记得也取消订阅:)

相关问题