Search code examples
angularobservableangular2-observables

How to Synchronize angular 2 or 4 life cycle hook and observables


I want to Synchronize my angular 2 life cycle hooks with Observable. For Example in the below Scenario.

**Temp Component**

    @Component({
    selector: 'temp-component',
    template: `<table [tableData]='tableData'>
    </table >`
})

export class TempComponent implements OnInit{
private data;
private tabledata;
   ngOnInit {
       this.getData(Dataurl).subscribe(
                        (data3: any) => {
                            this.data = data3;
                        },
                        (err: any) => {
                            console.error(err);
                        },
                        () => {
                            this.tabledata = this.data;
                            console.log('In temp component..', this.tabledata);
                        }

   }

getData(url: string): Observable<any> {
        return this.http.get(url)
        .map((res: Response) => res.json())
        .catch((err: Response) => Observable.throw(err.json().error));
    }

}

**Table Component :**

@Component({
    selector: 'table',
    template: `code for displaying table`
})

export class TableComponent implements OnInit{
   @Input tableData: any;
   ngOnInit{
      console.log('table Data..' , this.tableData);
   }
}


**Output :**
table Data.. undefined
In temp component.. (Displaying table data info)

In the above scenario I want the table data to be displayed as same as in temp component. Can anyone has any idea on how to make the table to displayed once the observable completes.


Solution

  • You need to use ngOnChange hook, Angular call this method when the component's input value change. I mean:

    .....
    export class TableComponent implements OnChanges {
    @Input() tableData:any;
    ngOnChanges(changes:SimplesChanges){
          if(changes['tableData']){
               console.log(this.tableData);
          }
    }
    

    hope can help!!!