gpt4 book ai didi

javascript - 更改检测 休息调用 Angular 2

转载 作者:太空宇宙 更新时间:2023-11-04 15:54:55 24 4
gpt4 key购买 nike

我是 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 可观察方法的内容,但我不知道这是否是一个好方法。如果问题不好或者我没有很好地解释我的问题,我很抱歉。

问候

最佳答案

从官方网站请求服务如下所示:

@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()),并且您的数据将被更新!

希望这个回答对你有帮助!

问候

关于javascript - 更改检测 休息调用 Angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42784674/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com