Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh component in angular 2

Tags:

angular

I am fairly new to angular 2, and trying to learn more about it.

My question here is: How do we refresh a component (re-invoke ngOnInit).

This component will be calling an API to retrieve some data from a database. and if a button is clicked, a PUT request will be sent to an API to update the data in the database. Since the change happens in the database instead of the component itself, I dont think ngOnChange or other change checking method will work. Here I am trying to let the ngOnInit be invoked again so the component can receive updated data.

I have tried router nagivate to refresh this page, but it does not work.

All the HTTP method happens in the another service file, I will not display them here since it's not relevant.

app.module.ts

@NgModule({
    imports: [
        RouterModule.forRoot([{path: 'data', component: DataComponent}]);
    ]
})

data.component.ts

@Component({
    template: `
        <button (click)= "onclick()">Click Me</button>
    `,
    ....
});

export class DataComponent implements OnInit{
    fetchData(): void{
        this.dataService.dataSessions().subscribe(
                data => this.data= data,
                error=> console.error(error),
                ()=> {}
        );
    }

     onclick(){
         this.dataChangeService.updateData().subscribe( response=> console.log(response));
         this.router.navigate['/data'];
     }

    ngOnInit(): void{
        this.fetchData();
    }

Any answer will be appreciated, I am always happy to learn more.

like image 957
Jay Shi Avatar asked Dec 19 '16 21:12

Jay Shi


1 Answers

Try to call the this.fetchData() method once your call to the backend is resolved. Something like:

response=> { this.fetchData() ...
like image 151
Fjut Avatar answered Nov 09 '22 20:11

Fjut