'How to push changes from service to component in angular 5 when ChangeDetectionStrategy.OnPush
I'm trying to optimize my angular app and try to use ChangeDetectionStrategy.OnPush.
I get a data from server in the services, and everything works when ChangeDetectionStrategy is don't specified.
Now it look like
export class Some{
public name: string;
}
@Injectable()
export class Service {
public items: Some[] = [];
constructor(http: HttpClient) {
this.getModel();
}
getModel{
this.http.get("some_url").subscribe((result: Some[])=>{
this.items = result;
}
}
}
@Component({
template: '<ul><li *ngFor="let item of service.items">{{item.name}}</li></ul>',
})
export class Component implements OnInit {
constructor(private service: Service) {
}
ngOnInit() {
}
}
How do push service data to component?
Solution 1:[1]
Is better if you use a different approach in you component and service.
In your component, items should be an Observable:
public items: Observable<Some[]>;
In the ngOnInit lifecycle hook, you will assign the the getItems method to the variable items.
ngOnInit() {
this.items = this.service.getItems();
}
getItems should look like this:
getItems(): Observable<Some[]> {
return this.http.get("some_url");
}
Your view can now use the async pipe to display the data:
<ul><li *ngFor="let item of (items | async)">{{item.name}}</li></ul>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | D M |
