Search code examples
angulartypescriptangular4-formsangular4-httpclient

Parsing API Response (object) from component to another component in Angular 4


I want to parse API response to another component

This is code from 'detail_item.component.ts', this code sent data to route "bookitem" in 'book_item.component.ts'

onSubmit(){
    this.appService.addItem(this.item).subscribe(item => {
      if(item.status ==200){
        this.router.navigate(['/bookitem'], {queryParams: {data: item.data}});
      }
    })
}

this is code from 'book_item.component.ts'

ngOnInit() {
    this.routeActive.queryParams.filter(params => params.data).subscribe(params => {
       this.book_item = params.data;
    });
}

when I console.log(this.book_item), what I got from it is [object object]. It should be contain json data.


Solution

  • If the type of item.data is object you need to convert it to string first which is like

    onSubmit(){
        this.appService.addItem(this.item).subscribe(item => {
          if(item.status ==200){
            this.router.navigate(['/bookitem'], {queryParams: {data: 
    JSON.stringify(item.data)}});
          }
        })
    }
    

    then you can parse it when you read it from the route on the other component

     ngOnInit() {
         this.book_item = JSON.parse(this.route.snapshot.queryParams['data']);
              }