简体   繁体   中英

Angular HTTP Observable @Input

here is my pseudo code:

service

getData(): Observable<MyData[]>{
  return this.http.get<Data[]>(`https://localhost/api/data`);
}

component:

myData: Data[];
[...]

ngOnInit(){
 this.myService.getData.subscribe( data => {
   this.myData = data;
   console.log(data);
 });
}

Template:

<app-subComponent *ngIf="data" class="cat-row" [data]='{"type": "row", "data": myData}'></app-subComponent> 

SubComponent:

@Input() data: any;

ngOnInit(){
 console.log(data);
}

My Problem: In this scenario, console.log gives me an empty array. If I don't pass this data attribute to my subcomponent via input, my first console.log gives me the correct array.

So maybe i miss something if i want to use http, observable, templating and @input in one "row" ?

Thanks for your help!

You should implement OnChanges then you can able to detect input when it changes.

  1. Import package

    import {Component, Input, OnChanges, SimpleChanges }

  2. Then implements Onchanges

     export class SubComponent implements OnChanges { @Input() data: any; constructor() { } ngOnChanges(changes: SimpleChanges){ if(changes["data"] && this.data){ // here you get the result } } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM