Javascript 更改检测Rest调用2
我是角度2的新手,有可能我不理解可观测的力量。我创建了一个使用rxjs提供REST调用的简单服务:Javascript 更改检测Rest调用2,javascript,rest,angular,rxjs,Javascript,Rest,Angular,Rxjs,我是角度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';
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
一种可观察的方法的文章,但我不知道这是否是一种好方法。
如果问题不好或者我没有很好地解释我的问题,我很抱歉
从官方网站请求服务获得的信息如下所示:
@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>
添加项目
每次单击此按钮时,它都会调用组件方法addFoo
并执行postFoo()
。当postFoo()
完成时,它将执行getFoo()
(此处displayFoo()
),您的数据将被更新
希望这个答案对你有帮助
你想要这样的东西吗?我试着写一个例子:在第一次调用时,我的方法返回了一个包含2个元素的对象。5分钟后,有人在这个对象中添加了另一个元素,但我仍然看到了旧对象。要查看新对象,我必须刷新页面(因此组件调用该方法)所以我想开发一种方法,它可以监听数据的变化,然后自动重新调用。添加新数据是由你的应用程序处理的还是来自其他地方?它来自其他地方。每次用户添加数据时,你都必须执行你的get
方法进入post
方法,get
方法将被调用。谢谢,但添加元素的用户不一样。是的,我知道,但您需要指定用户的角色,但这只是一个示例,向您展示如何处理此问题!:D