【问题标题】:Change detection Rest call Angular 2变更检测 Rest call Angular 2
【发布时间】:2017-03-14 20:02:36
【问题描述】:

我是 Angular 2 的新手,我可能不了解可观察的力量。我创建了一个使用 rxjs 提供 REST 调用的简单服务:

import {Injectable} from '@angular/core';
import {Http, Response, Headers} from '@angular/http';
import {Observable} from 'rxjs/Rx';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';


@Injectable()
export class DataService {


  constructor(private http: Http) { }



  postFoo(){

    this.http.get('http://localhost:8080/Sample')
      .map(res=>res.json())

      .subscribe(

        res=>console.log(res)

      );



  }

}

我在我的组件中以这种方式调用了这个方法:

ngOnInit(){

    this._dataService.postFoo();

  }

这一切都很好。现在我想找到一种方法,每次数据发生变化时,组件都会重新调用此方法。我读了一些关于.distinctUntilChanged 的可观察方法,但我不知道这是否是一个好方法。 如果问题不好或者我没有很好地解释我的问题,我很抱歉。

问候

【问题讨论】:

  • 你想要这样的东西吗? stackoverflow.com/questions/36261829/…
  • 我试着写一个例子:在第一次调用我的方法时返回了一个包含 2 个元素的对象。 5 分钟后,有人在这个对象中添加了另一个元素,但我看到的是旧对象。要查看新对象,我必须刷新页面(以便组件调用该方法),因此我想开发一种方法来监听数据的变化,它会自动重新调用。
  • 添加的新数据是由您的应用处理的还是来自其他地方?
  • 它来自其他地方
  • 你必须将你的get方法执行到post方法中,每次用户添加数据,当它完成时,get方法将被调用。

标签: javascript rest angular rxjs


【解决方案1】:

从官网请求服务是这样的:

@Injectable()
export class DataService {


  constructor(private http: Http) { }


  postFoo(){

    return this.http.post('http://localhost:8080/Sample')
      .map(this.parseData)

  }

   getFoo(){

      return this.http.get('http://localhost:8080/Sample')
      .map(this.parseData)

  }
  parseData(res: any): void {
      let response = res.json();
      return response;
  }

}

进入你的组件:

ngOnInit(){
    this.displayFoo();
}

displayFoo() {
    this._dataService.getFoo().subscribe(
         (response) => {
             // display response
         }
    );
}

addFoo() {
     this._dataService.postFoo().subscribe(
         (response) => {
             this.displayFoo();
         }
    );
}

在这里,我创建了名为addFoo 的方法,它将从您的服务中执行.postFoo()。 假设您有一个添加项目的按钮

<button (click)="addFoo()">Add item</button>

每次点击这个按钮,都会调用component方法addFoo并执行postFoo()。当postFoo() 完成时,它会执行getFoo()(这里是displayFoo())并且你的数据会被更新!

希望这个答案对你有所帮助!

问候

【讨论】:

  • 谢谢,但是添加元素的用户不一样。
  • 是的,我知道,但是您需要指定用户的角色,但这只是向您展示的示例,您如何解决这个问题! :D
猜你喜欢
  • 2017-09-28
  • 2017-05-25
  • 2016-05-29
  • 1970-01-01
  • 2017-05-04
  • 2017-02-09
  • 1970-01-01
  • 1970-01-01
  • 2016-12-16
相关资源
最近更新 更多