【发布时间】:2017-03-21 10:36:31
【问题描述】:
在我的服务中,我有一个从服务器获取一些数据的函数。我的应用程序的几个部分在初始化时调用此函数。我想做的是:如果已经发送了一个请求,则另一个等待它的响应(他们不需要自己提出请求)。
所以我的代码是:
@Injectable()
export class UserService implements OnInit {
ngOnInit(){
this.getUserInformations();
};
public getUserInformations(forceRefresh?: boolean): Observable<Object>{
if(this.userInformationsLastObservable == null) {
console.log('Making a request'); // called only once at init
this.userInformationsLastObservable = this.http.get(this.baseUrl + "informations")
.map((result: Response) => {
console.log('map is called'); // called 5 times at init
let userInformations = result.json();
/* So future calls will perform a new request */
this.userInformationsLastObservable = null;
return userInformations;
});
}
return this.userInformationsLastObservable;
};
}
有几个组件这样称呼它:
@Component({
selector: 'app-leaderboard',
templateUrl: 'leaderboard.component.html',
styleUrls: ['leaderboard.component.css'],
providers: []
})
export class LeaderboardComponent implements OnInit
{
ngOnInit(){
this.userService.getUserInformations().subscribe((userInformations) => {
this.userInformations = userInformations;
/* this function does not make any call to the User service */
this.refresh();
}, () => {
this.isLoading = false;
});
};
}
问题是:从控制台的网络面板中,我看到在初始化时发送了 5 个请求。并且“调用地图”也打印了 5 次,而“发出请求”只调用了一次。
我做错了什么?
【问题讨论】:
-
您是否真的在网络选项卡中看到了 5 个网络请求?可以截图吗?
-
是的 :)(编辑了我的帖子)
-
好的,我现在很确定这与 Angular 2 服务不是单例的事实有关(参见 stackoverflow.com/a/36200020/6408940)。会做一些测试
-
其实没有。 “发出请求”仅打印一次这一事实表明它们都使用相同的实例(在应用程序模块级别声明)。
-
this.refresh();在做什么?
标签: angular rxjs angular2-http angular2-observables