响应未定义

Response is undefined

我已经学习了 Heroes 教程,现在我正尝试从 MVC 网络 api rest 服务中检索我的英雄数据。我在 hero.service:

中修改了 GetHeroes() 方法
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';

import { HttpClient } from '@angular/common/http';

export class Hero {
  constructor(public Id: number, public HeroName: string, public Location: string) { }
}

@Injectable()
export class HeroService {

  constructor(private http: HttpClient) { }

  results: Observable<string[]>;

  private location: string;

  getHeroes(): Observable<Hero[]> {
      return this.http.get('http://localhost:50125/api/heroes')
          .map((response: Response): Hero[] => JSON.parse(response['_body']))
          .catch(error => Observable.throw(error));
  }

  getHero(id: number | string) {
    return this.getHeroes()
      // (+) before `id` turns the string into a number
      .map(heroes => heroes.find(hero => hero.Id === +id));

  }

}

我正在从我的组件调用服务方法:

import 'rxjs/add/operator/switchMap';
import { Observable } from 'rxjs/Observable';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, ParamMap } from '@angular/router';

import { Hero, HeroService } from './hero.service';

@Component({
  template: `
    <h2>HEROES</h2>
    <ul class="items">
      <li *ngFor="let hero of heroes$ | async"
        [class.selected]="hero.Id === selectedId">
        <a [routerLink]="['/hero', hero.Id]">
          <span class="badge">{{ hero.Id }}</span>{{ hero.HeroName }}
        </a>
      </li>
    </ul>
  `
})
export class HeroListComponent implements OnInit {
  heroes$: Observable<Hero[]>;

  private selectedId: number;

  constructor(
    private service: HeroService,
    private route: ActivatedRoute
  ) {}

  ngOnInit() {
    this.heroes$ = this.route.paramMap
      .switchMap((params: ParamMap) => {
        // (+) before `params.get()` turns the string into a number
        this.selectedId = +params.get('id');
        return this.service.getHeroes();
      });
  }

}

我的英雄 api 控制器看起来像这样:

using HeroesService.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json;

namespace HeroesService.Controllers
{
    public class HeroesController : ApiController
    {
        // GET: api/Heroes
        public List<Hero> Get()
        {
            List<Hero> heroes = new List<Hero>();

            Hero superman = new Hero();
            superman.Id = 10;
            superman.HeroName = "Superman";
            superman.Location = "Los Angeles, California";
            heroes.Add(superman);

            Hero batman = new Hero();
            batman.Id = 11;
            batman.HeroName = "Batman";
            batman.Location = "Chicago, Illinois";
            heroes.Add(batman);

            return heroes;
        }
    }
}

我可以在 Chrome 的“网络”选项卡中看到如下所示的数据:

[{"Id":10,"HeroName":"Superman","Location":"Los Angeles, California"},{"Id":11,"HeroName":"Batman","Location":"Chicago, Illinois"}]

不幸的是,我收到如下所示的错误(可能意味着响应数据未定义):

ERROR SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse () at MapSubscriber.eval [as project] (hero.service.ts:34) at MapSubscriber._next (map.ts:75) at MapSubscriber.Subscriber.next (Subscriber.ts:95) at MapSubscriber._next (map.ts:80) at MapSubscriber.Subscriber.next (Subscriber.ts:95) at FilterSubscriber._next (filter.ts:95) at FilterSubscriber.Subscriber.next (Subscriber.ts:95) at MergeMapSubscriber.notifyNext (mergeMap.ts:151) at InnerSubscriber._next (InnerSubscriber.ts:17)

您可以利用 HttpClient.get 能够为您处理 JSON 数据这一事实。使用以下代码告诉 HttpClient 响应类型为 Hero[] 并停止对 mapcatch 的调用:

 return this.http.get<Hero[]>('http://localhost:50125/api/heroes');

我希望你得到 undefined,因为 response 不会有 属性 _body

您使用的是新版 HttpClient,但使用方式与旧版 http 相同。

getHeroes(): Observable<Hero[]> {
  return this.http.get('http://localhost:50125/api/heroes')
    .map((response: Response): Hero[] => JSON.parse(response['_body']))
    .catch(error => Observable.throw(error));
}

应该是

getHeroes(): Observable<Hero[]> {
  return this.http.get<Hero[]>('http://localhost:50125/api/heroes');
}

您只需订阅即可,不需要 JSON.parse。