下面的代码是我目前拥有的代码的简化版本:
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
会先调用NameService
类的getName
方法。 getName
将进行 ajax 调用并返回一个可观察对象。
接下来,name2.component.ts
也会调用NameService
类的相同的getName
方法,而getName
也将执行相同的 ajax 调用并返回一个 observable。
是否可以使用 rxjs,当 NameService
中的 getName
方法进行第一次 ajax 调用时,它会存储 ajax 调用的结果.对 getName
方法的任何后续函数调用都将返回第一个 ajax 调用的缓存结果,并且不会执行另一个冗余的 ajax。
最佳答案
你可以多次订阅 Observable,所以如果你只想保存两个组件之间共享数据的第二个网络请求,你可以像这样在你的服务中缓存它:
@Injectable()
export class NameService {
const nameURL = "http://www.example.com/name";
private cache: Observable<any>;
getName() {
return this.cache || this.cache = this.http.get(nameURL);
}
}
关于javascript - RxJS 5 Observable 和 Angular2 http : Call ajax once, 保存结果,后续ajax调用使用缓存结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41551280/