在 Angular 4 中解析从组件到另一个组件的 API 响应(对象)

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

我想解析 API 对另一个组件的响应

这是来自 'detail_item.component.ts' 的代码,此代码将数据发送到 'book_item.component.ts'

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

这是来自 'book_item.component.ts'

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

当我console.log(this.book_item)的时候,得到的是[object object]。它应该包含 json 数据。

由于您正尝试在查询字符串中传递对象,因此您 [object object] 完全没问题。此外,您不能在查询字符串中传递对象,您可以传递可轻松转换为字符串的值,如数字。

如果item.data的类型是object,你需要先把它转换成字符串,比如

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

然后在其他组件上从路由读取就可以解析了

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