简体   繁体   English

在Angular 2中使用subscribe获得http响应后获取[object Object]

[英]Getting [object Object] after getting http response using subscribe in Angular 2

ProductService.ts 产品服务

   getProduct(id: number): Observable<IProduct> {

    return this._http.get(this._productUrl + '/GetById/' + 
           id).map((response: Response) => <IProduct>response.json())           
        .catch(this.errorHandler);     
}

ProductDetailComponent.ts ProductDetailComponent.ts

   getProduct(id: number) {
    this._productService.getProduct(id).subscribe(
        res => {               
            console.log('before component ' + res);     
            this.product = res;
            console.log('after component ' + res);                
        },
        error => this.errorMessage = <any>error),
        console.log('execution complete'); 
}

When receiving result in subscribe it is coming as 当订阅中收到结果时,它将作为
execution complete, before component [object Object], after component [object Object] 执行完成,在组件[object Object]之前,在组件[object Object]之后

You are using string concatenation (using the + sign). 您正在使用字符串连接(使用+号)。 This way, Javascript will first convert the Object to a string ( [object Object] ). 这样,JavaScript会首先将Object转换为字符串( [object Object] )。 If you don't want that, you could try it like this: console.log('before component', res) . 如果您不希望这样做,可以尝试如下操作: console.log('before component', res)

Note the comma, not a + . 请注意逗号,而不是+ This passes the object to console.log as a separate parameter, allowing your browser or CLI to do the rendering. 这会将对象作为单独的参数传递到console.log ,从而允许您的浏览器或CLI进行呈现。 For instance, this way (in the browser) you can expand or collapse the object. 例如,通过这种方式(在浏览器中),您可以展开或折叠对象。

你需要做JSON.stringify

console.log('before component ' + JSON.stringify(res));  

You could also do the following: 您还可以执行以下操作:

console.log('before component',JSON.stringify(res,undefined,2))

to pretty print [Object object] as json object. 漂亮地打印[Object object]作为json对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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