typescript 在Angular 2中映射http响应时获取[object Object]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41627548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:10:01  来源:igfitidea点击:

Getting [object Object] while mapping http response in Angular 2

angulartypescriptasp.net-coreangular-services

提问by San Jaisy

I am getting an [object Object] while using Observable map in angular 2.

我在 angular 2 中使用 Observable 贴图时得到一个 [object Object]。

Here is the response object from the API service.

这是来自 API 服务的响应对象。

{
  "isSuccess": true,
  "message": "Connection Successfull",
  "data": [
    {
      "marketId": 1,
      "city": "san",
      "cityF": "san",
      "name": null,
      "nameF": "hello",
      "sortOrder": 1,
      "isActive": true
    },
    {
      "marketId": 2,
      "city": "san",
      "cityF": "san",
      "name": null,
      "nameF": "hello",
      "sortOrder": 1,
      "isActive": true
    },
    {
      "marketId": 3,
      "city": "san",
      "cityF": "san",
      "name": null,
      "nameF": "hello",
      "sortOrder": 1,
      "isActive": true
    },
    {
      "marketId": 4,
      "city": "san",
      "cityF": "san",
      "name": null,
      "nameF": "hello",
      "sortOrder": 1,
      "isActive": true
    }
  ],
  "exceptionErrorMessage": null,
  "errorCode": 0,
  "successMessage": null
}

Here is the model I have created to map with the response.

这是我创建的用于映射响应的模型。

export class MarketViewModel 
{
public isSuccess: boolean;
public message : string;
public successMessage : string;
public exceptionErrorMessage : string;
public errorCode: number;
public data: MarketListObject[];

}
export class MarketListObject 
{
    public marketId : number;
    public city: string;
    public cityF : string;
    public name : string;
    public nameF : string;
    public sortOrder : number;
    public isActive : boolean; 
}

Service class to call the http and map the response.

调用 http 并映射响应的服务类。

import { Headers, RequestOptions } from '@angular/http';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { MarketViewModel} from "../ViewModel/Market.ViewModel";
import { Injectable }     from '@angular/core';
import { Http, Response } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class DashBoardService {
    private MarketUrl = "DashBoard/GetMarketList";
    private ResponseData: any;
    constructor(private http: Http, private router: Router, private  marketModel : MarketViewModel) {}

    public GetMarketListCall() :Observable<MarketViewModel> {
         return this.http.get(this.MarketUrl).map(this.extractData)
                    .catch(this.handleError);
    } 
private extractData(res: Response) {
    let body = res.json();
        console.log("Body Data = "+body.data);
    return body.data || { };
  }

Here is the Component.ts which is calling Service.ts

这是调用 Service.ts 的 Component.ts

import { Component } from '@angular/core';
import { MarketViewModel} from "../ViewModel/Market.ViewModel";
import { DashBoardService} from "../Service/DashBoard.Service";
import { Observable } from 'rxjs/Observable';

 @Component({
     selector: 'Market-app',
    templateUrl: 'DashBoard/MarketListView',
    providers: [DashBoardService, MarketViewModel]
 })

export class MarketComponent {
  constructor(private DashBoardservice: DashBoardService, private  marketModel : MarketViewModel) {
   }

ngOnInit() {
        this.DashBoardservice.GetMarketListCall().subscribe(
                               data => {this.marketModel = data;
                                    console.log("this"+this.marketModel); }, 
                                err => {console.log(err);});
}
}

When I see to the console I am getting [object Object]response. Where is the mistake I am not able to figure it out

当我看到控制台时,我收到了[object Object]响应。我无法弄清楚的错误在哪里

采纳答案by ranakrunal9

You have to change your DashBoardServiceas below as you are have to return MarketListObjectarray as observable not MarketViewModel:

您必须更改DashBoardService如下,因为您必须将MarketListObject数组返回为可观察的而不是MarketViewModel

@Injectable()
export class DashBoardService {
  private MarketUrl = "DashBoard/GetMarketList";
  private ResponseData: any;

  constructor(private http: Http, private router: Router, private  marketModel : MarketViewModel) {}

  public GetMarketListCall() :Observable<MarketListObject[]> {
     return this.http.get(this.MarketUrl).map(this.extractData)
                .catch(this.handleError);
  } 

  private extractData(res: Response) {
    let body = res.json();
    console.log("Body Data = "+body.data);
    return body.data || [];
  }
}

Also there is no need to pass MarketViewModelas providers inside MarketComponentso remove MarketViewModelfrom MarketComponentproviders list and change your component as below .

也不需要在MarketViewModel内部作为提供者传递,MarketComponent因此MarketViewModelMarketComponent提供者列表中删除并如下更改您的组件。

import { Component } from '@angular/core';
import { DashBoardService} from "../Service/DashBoard.Service";
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'Market-app',
  templateUrl: 'DashBoard/MarketListView',
  providers: [DashBoardService]
})
export class MarketComponent {

  public marketList: any[];

  constructor(private dashBoardservice: DashBoardService) {
  }

  ngOnInit() {
    this.dashBoardservice.GetMarketListCall().subscribe((data) => { 
      this.marketList = data;
      console.log("this" + this.marketList);
    },(err) => {
      console.log(err);
    });
  }
}

回答by AJT82

You have a problem with your extractData, you want the response as it is, to match your MarketViewModel, so you need to remove the datafrom that method and also to return an empty object if there is no response:

您的 有问题extractData,您希望响应按原样匹配您的MarketViewModel,因此您需要data从该方法中删除 ,如果没有响应,还需要返回一个空对象:

private extractData(res: Response) {
  let body = res.json();
  return body || {};
}

Some pointers:

一些提示:

  • In your Service and MarketComponent you do not need to inject the MarketViewModel in your constructor.
  • You need to declare a variable marketModelin your component, to be able to use this.marketModel.
  • In component you have declared method ngOnInit, but not implemented it in your component
  • 在您的 Service 和 MarketComponent 中,您不需要在构造函数中注入 MarketViewModel。
  • 您需要marketModel在组件中声明一个变量,才能使用this.marketModel.
  • 在组件中你已经声明了方法ngOnInit,但没有在你的组件中实现它

When testing your app it worked:

在测试您的应用程序时,它起作用了:

getMarketListCall(): Observable<MarketViewModel>{
    return this.http.get('theUrl')
        .map(res => res.json()) // or use the 'extractData'
        // .catch(this.handleError);
}

Your component:

您的组件:

marketmodel: MarketViewModel

ngOnInit() {
    this.DashBoarservice.GetMarketListCall()
       .subscribe(data => {
          this.marketModel = data;
        },
        err => { console.log(err); 
    });
}

Your view, you should wrap your html in an if-statement, since your data gets retrieved asynchronously:

您的观点,您应该将 html 包装在 if 语句中,因为您的数据是异步检索的:

e.g:

例如:

<div *ngIf="marketModel"> <!-- Here! -->
  <h2>MarketModel Message: {{marketModel.message}}</h2>
  <div *ngFor="let data of marketModel.data">Id: {{data.marketId}} </div>
</div><br>

We need to remember though this code works wonderfully, we have not actually casted the response to be of instances of your classes. If you wish to do that, I suggest the following link with some great answers :) How do I cast a JSON object to a typescript class

我们需要记住,虽然这段代码工作得很好,但我们实际上并没有将响应转换为您的类的实例。如果您想这样做,我建议使用以下链接并提供一些很好的答案:)如何将 JSON 对象转换为打字稿类