【问题标题】:Response is undefined响应未定义
【发布时间】:2018-03-11 18:22:19
【问题描述】:

我已经按照英雄教程进行操作,现在我正在尝试从 MVC Web api 休息服务中检索我的英雄数据。我在 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: 位置 0 处 JSON 中的意外标记 u 在 JSON.parse() 在 MapSubscriber.eval [作为项目] (hero.service.ts:34) 在 MapSubscriber._next (map.ts:75) 在 MapSubscriber.Subscriber.next (Subscriber.ts:95) 在 MapSubscriber._next (map.ts:80) 在 MapSubscriber.Subscriber.next (Subscriber.ts:95) 在 FilterSubscriber._next (filter.ts:95) 在 FilterSubscriber.Subscriber.next (Subscriber.ts:95) 在 MergeMapSubscriber.notifyNext (mergeMap.ts:151) 在 InnerSubscriber._next (InnerSubscriber.ts:17)

【问题讨论】:

  • 你能在服务中登录吗?它在 Angular 方面哪里失败了

标签: json angular asp.net-web-api asp.net-web-api2


【解决方案1】:

您可以利用HttpClient.get 能够为您处理 JSON 数据这一事实。使用以下代码告诉HttpClient 响应类型是Hero[],然后将您的呼叫同时挂断mapcatch

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

我希望你得到一个undefined,因为response 没有属性_body

【讨论】:

    【解决方案2】:

    您使用的是新的 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 它。

    【讨论】:

      猜你喜欢
      • 2021-06-21
      • 2021-05-26
      • 2019-01-20
      • 2021-10-28
      • 2014-12-30
      • 2012-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多