javascript
ajax和rxjs,javascript – RxJS 5 Observable和Angular2 http:调用ajax一次,保存结果,随后的ajax调用使用缓存结果...
下面的代碼是我目前擁有的簡化版本:
name.service.ts@Injectable()
export class NameService {
const nameURL = "http://www.example.com/name";
getName() {
return this.http.get(nameURL);
}
}
name1.component.ts@Component({
templateUrl: './name1.component.html',
styleUrls: ['./name1.component.css']
})
export class Name1Component implmenets OnInit {
private name1;
constructor(
private nameService: NameService
){}
ngOnInit() {
this.setupName();
}
private setupName() {
this.nameService.getName()
.subscribe(
resp => this.name1 = resp,
error => this.name1 = "unknown"
);
}
}
name2.component.ts@Component({
templateUrl: './name2.component.html',
styleUrls: ['./name2.component.css']
})
export class Name2Component implmenets OnInit {
private name2;
constructor(
private nameService: NameService
){}
ngOnInit() {
this.setupName();
}
private setupName() {
this.nameService.getName()
.subscribe(
resp => this.name2 = resp,
error => this.name2 = "unknown"
);
}
}
這是我想要做的,name1.component.ts將首先調(diào)用NameService類的getName方法.然后getName將進行ajax調(diào)用并返回一個observable.
接下來,name2.component.ts也將調(diào)用NameService類的相同getName方法,getName也將執(zhí)行相同的ajax調(diào)用并返回一個observable.
是否可以使用rxjs,當NameService中的getName方法進行第一次ajax調(diào)用時,它會存儲ajax調(diào)用的結(jié)果.對getName方法的任何后續(xù)函數(shù)調(diào)用將返回第一個ajax調(diào)用的緩存結(jié)果,而不執(zhí)行另一個冗余的ajax.
最佳答案 您可以多次訂閱Observable,因此,如果您只想保存第二個網(wǎng)絡請求以便在兩個組件之間共享數(shù)據(jù),您可以將其緩存在您的服務中,如下所示:@Injectable()
export class NameService {
const nameURL = "http://www.example.com/name";
private cache: Observable;
getName() {
return this.cache || this.cache = this.http.get(nameURL);
}
}
總結(jié)
以上是生活随笔為你收集整理的ajax和rxjs,javascript – RxJS 5 Observable和Angular2 http:调用ajax一次,保存结果,随后的ajax调用使用缓存结果...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c++对象回收string类型成员时co
- 下一篇: matlab 思维数组_matlab多维