1

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?

2
  • 1
    Please, share some code! Commented Mar 19, 2018 at 12:25
  • I added simple example Commented Mar 19, 2018 at 12:39

1 Answer 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>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.