Reputation: 103
I have a problem where Angular2 makes the same request twice. I don't know why, though, because I have only one time a subscribe on the Observable. Here is my code:
My service looks like this:
getProjects(): Observable<Project[]> {
return this.http.get(this.url)
.map(this.mapProjects)
.catch(this.handleError);
}
private mapProjects(response: Response): any {
const mappedProjects = response.json();
return mappedProjects;
}
My component looks like this:
export class ProjectListComponent implements OnInit {
// List of projects
listProjects: Project[] = [];
constructor(private projectListService: ProjectListService) {
}
public getProjectList() {
this.projectListService.getProjects()
.subscribe(
projects => {
this.listProjects = projects;
},
error => {
// error handling
});
}
}
In the network tab of the Chrome Developer Tools I see the request is made two times, once the initiator is zone.js, the other time it just says "Other". Can anyone explain this behaviour?
Upvotes: 10
Views: 5003
Reputation: 12378
Without seeing the code I can only guess that your component is opened by the router, and you've configured a resolver that invokes getProjects(). In such case the resolver implicitly subscribes to the Observable returned by getProjects(). Hence you have a situation with two invocations of subscribe(): one explicit and one implicit.
Upvotes: 1
Reputation: 2180
I think that is preflight request. These are made before the actual request. Your preflight response needs to acknowledge these headers in order for the actual request to work.Once you send this response to the preflight request, the browser will make the actual request. https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests
Upvotes: 9
Reputation: 56936
not sure without seeing your entire codebase but this will fix it ...
.getProjects().first().subscribe( ... etc
you will need to add
import 'rxjs/add/operator/first';
The first operator ensure subscribe is only called once. However, if you need it called multiple times (e.g. later on when an event occurs) then this will not be your solution.
PS subscribe is called every time the Observable stream emits. If the stream is emitting twice then subscribe is called twice. You can debug the Observable to see what it is emitting using do()
it would call it twice if ...
1 - you subscribe twice and it emits once, make sure you are not calling subscribe more than once
2 - it emits twice
Upvotes: 0