I made a small MEAN stack based application, and used a method of a service inside the Component life cycle. I used DoCheck life cycle to fetch new value from server whenever a change in the value is made. I though the Life cycle will be Executed whenever the value is changed, or in fixed intervals. But the DoCheck Life cycle hook is getting executed infinitely and sending infinite requests to the server.
The Component screenshot is as follows:
export class CommentsComponent implements DoCheck {
comments: Comment[] = [];
ngDoCheck() {
this.commentService.getComments().subscribe((result) => {
this.comments = result.comments;
}, (error) => console.log(error));
}
}
What i expected is the life cycle hook will send request to the server to fetch new comments (that other users may have posted) whenever they actually post or in fixed intervals, but the life cycle hook is sending request infinitely. (Sorry that screenshot from Chrome Developer tools, my PC freezes as soon i load the application).
The Service Code is as follows:
export class CommentService {
getComments () {
return this.http.get('http://www.localhost:3000/getcomment').map(res => res.json());
}
}
PS: my application runs on port 4200, while my backend runs on port 3000 The Complete Application repository is here.
If i use OnInit lifecycle hook, then the request is made once the component is made, though it is not what i want, but it shows that the service/use of service is not wrong (incorrectly coded), the Life Cycle hook is sending the requests.
ngDoCheckget called on each change detection run, you shouldn't be usingngDoCheckunless you have special case. Read docs here. Why you don't you call your service fromngOnInitthat will call on specified interval(using RxJS perhaps) - Pankaj Parkar