[英]Subscribing to observable generates second http get (HttpClient)
Why when adding the subscription below do I see a second call to get the JSON in the chrome developer network tab? 为什么在下面添加订阅时,我在Chrome开发人员网络标签中看到第二个调用以获取JSON?
The second call is a few milliseconds later and shows a full request & response 第二个呼叫是在几毫秒后,并显示完整的请求和响应
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
repositories: Observable<Array<any>>;
constructor(http: HttpClient) {
const path = 'https://api.github.com/search/repositories?q=angular&sort=stars&order=desc';
this.repositories = http.get<any>(path).pipe(map(obj => obj.items));
// adding this subscription creates
// a second call for the JSON?
this.repositories.subscribe(next => {
localStorage['repoCache'] = JSON.stringify(next);
});
}
}
You probably have something like this on your template: 您的模板上可能有以下内容:
<div *ngIf="repositories">
<li *ngFor="let repository of (repositories | async)">{{repository.name}}</li>
</div>
"async" generates a subscription and you have another one on the component. “异步”将生成一个订阅,并且该组件上还有一个订阅。 Each subscription will fire the observable, thus generating two HTTP calls.
每个订阅将触发可观察对象,从而生成两个HTTP调用。
Lastly, I would recommend not to do http calls on the constructor, instead implement the "OnInit" method, which is a better place in the lifecycle of a component for that type of work. 最后,我建议不要在构造函数上进行http调用,而应实现“ OnInit”方法,对于这种类型的工作,这是组件生命周期中更好的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.