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

时间:2017-01-13 04:48:38

标签: angular typescript asp.net-core angular-services

在角度2中使用Observable map时,我得到一个[object Object]。

以下是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
}

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

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; 
}

服务类调用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 || { };
  }

这是调用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);});
}
}

当我看到控制台时,我得到 [object Object] 响应。哪个错误我无法弄清楚

2 个答案:

答案 0 :(得分:4)

您的extractData问题,您希望答案原样与您的MarketViewModel匹配,因此您需要从该方法中移除data并返回如果没有响应,则为空对象:

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

一些指示:

  • 在您的Service and MarketComponent中,您不需要注入 构造函数中的MarketViewModel。
  • 您需要在组件中声明变量marketModel 能够使用this.marketModel
  • 在组件中,您已声明方法ngOnInit,但未在组件中实现

在测试您的应用时,它有效:

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

您的组件:

marketmodel: MarketViewModel

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

您的观点,您应该将您的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>

我们需要记住,虽然这段代码运行得非常好,但我们实际上还没有将响应转换为类的实例。如果您希望这样做,我建议以下链接提供一些很好的答案:) How do I cast a JSON object to a typescript class

答案 1 :(得分:1)

您必须更改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 || [];
  }
}

此外,无需将MarketViewModel作为MarketComponent内的提供者传递,因此请从MarketViewModel提供商列表中删除MarketComponent,然后按以下方式更改您的组件。

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);
    });
  }
}