Angular 2 Promise始终返回null ZoneAwarePromise

时间:2016-10-13 20:28:26

标签: angular asp.net-core

几天前,我盯着学习ASP.NET Core和Angular 2.到目前为止,这很好,除了今天。 我对问题的一点介绍。

我有一个非常简单的Web Api控制器。

[Route("api/[controller]")]
public class HomeController : Controller
{       
    private readonly ForumSystemDbContext dbContext;

    public HomeController(ForumSystemDbContext dbContext)
    {
        this.dbContext = dbContext;
    }

    [HttpGet]
    public IActionResult Index()
    {
        var posts = this.dbContext.Posts
            .Include(x => x.PostTag)
            .ThenInclude(x => x.Tag)
            .Select(x => new
            {
                Title = x.Title,
                Content = x.Content,
                Tags = x.PostTag.Select
                (
                    y => new
                    {
                        name = y.Tag.Name
                    }
                )
            });

        return this.Json(posts);
    }
}

角度服务:

import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

export class Post {
    Content: string;
    Title: string;
    Tags: Tag[];
}

export class Tag {
    Name: string;
}

@Injectable()
export class HomeService {
    private postsUrl = 'http://localhost:54692/api/home';

    constructor(private http: Http) { }

    getPosts(): Promise<Post[]> {
        return this.http.get(this.postsUrl)
                        .toPromise()
                        .then(this.extractData)
                        .catch(this.handleError);
    }

    private handleError(error: any) {
        // In a real world app, we might use a remote logging infrastructure
        // We'd also dig deeper into the error to get a better message
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); // log to console instead
        return Promise.reject(errMsg);
    }

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

        return body.data || {};
    }
}

最后是home.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { HomeService } from '../services/home.service';

export class Post {
    Content: string;
    Title: string;
    Tags: Tag[];
}

export class Tag {
    Name: string;
}

@Component({
    templateUrl: 'app/home/home.html'
})
export class HomeComponent implements OnInit {
    posts: Post[] = [];

    constructor(
        private router: Router,
        private homeService: HomeService) {
    }

    ngOnInit(): void {
        this.homeService.getPosts()
            .then(posts => this.posts = posts);
    }
}

问题是posts变量总是一个空数组。当我记录

this.homeService.getPosts() 

它的回报

ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array[0]}

我已阅读官方的角度2文档https://angular.io/docs/ts/latest/guide/server-communication.html#!#promises,但不幸的是,它并不适用于我的情况。

所以,我想知道我的错误在哪里?

是某种配置问题还是其他什么?

2 个答案:

答案 0 :(得分:3)

尝试改变:

private extractData(res: Response) {
  return res.json();
}

data

您的回复中没有[{"Title":"title1","Content":"","Tags":[]},{"Title":"title2","Content":"","Tags":[]}] 属性

nombre

答案 1 :(得分:0)

尝试使用此方法进行服务。

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class HomeService {
  private postsUrl = 'http://localhost:54692/api/home';
  constructor(private http:Http) { }

  getPosts(){
    return this.http.get(this.postsUrl).map(
        res => res.json()
    );
  }

}

并从下面的组件中使用它。

getPosts(){
    this.homeService.getPosts().subscribe(
      data => {
        this.posts = data;
      },
      error => {

      },
      () => {}
    );
  }

此处,this.homeService是您服务的一个实例,this.posts只是一个本地变量,将由您从Web API返回的帖子填充。

回家帮助。