角度2属性' X'类型' Y'

时间:2016-10-05 12:16:16

标签: angular angular2-services

我对角度2很新,我试图重构之前以角度1编写的应用程序。

这是我的好东西组件(女巫基本上显示了从wordpress博客的好东西类别中提取的帖子)

import { Component, OnInit } from '@angular/core';
import { ConfigService } from '../config/config.service';
import { FetchGoodiesService } from '../shared/fetch-goodies.service'
import { Goodie } from '../shared/goodie'



@Component({
    selector: 'app-goodies',
    templateUrl: './goodies.component.html',
    styleUrls: ['./goodies.component.css'],
    providers: [FetchGoodiesService, ConfigService],
})
export class GoodiesComponent implements OnInit {

    private goodies: Goodie[] = []
    private endpoint: string

    constructor(private _fetchGoodiesService : FetchGoodiesService) { }

    public ngOnInit() {
        this._fetchGoodiesService.getGoodies().subscribe( data => {
            this.goodies = data.posts 
            console.log("this goodies", data) 
        });
    }

}

然后我得到了我的Goodie界面:

export interface Goodie {
    status: string
    pages: number
    count: number
    count_total: number
    posts: any
} 

我的好东西服务从端点获取数据

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { ConfigService } from '../config/config.service'
import { Goodie } from '../shared/Goodie'

import 'rxjs/Rx'`enter code here`
import 'rxjs/add/operator/map'


@Injectable()
export class FetchGoodiesService {

    private baseUrl: string
    private endpoints: any
    constructor(
        private _http: Http,
        private _configService: ConfigService,
    ) {
        this.endpoints = this._configService.getProperty("endpoints")
        this.baseUrl = this.endpoints.baseUrl
    }

    public getGoodies(): Observable<Goodie[]> {
        return this._http.get( this.baseUrl + this.endpoints.getCategoryPost + 'goodies' )
                .map(res => res.json())
    }


    private handleError(error) {
        console.log(error)
    }

}

这是我从终点

回归的json的模拟
{
    "status": "ok",
    "count": 9,
    "count_total": 9,
    "pages": 1,
    "posts": [
        {..},
        {..}
    ]
}

我的问题是编译器在goodies组件的这一行上给我一个错误: this.goodies = data.posts 我得到:财产&#39;帖子&#39;类型&#39; Goodie []&#39;

上不存在

我认为声明帖子:接口上的任何内容都可以工作,但它不会。 感谢任何可以帮助我的人。

1 个答案:

答案 0 :(得分:0)

我找到了一个让应用程序正常工作的解决方法,但是我不喜欢它。我想知道我的问题是否有明确的解决方案。

这是解决方案代码:

export class GoodiesComponent implements OnInit {
    private res:any
    private goodies: Goodie[] = []
    private endpoint: string

    constructor(private _fetchGoodiesService : FetchGoodiesService) { 
    }

    public ngOnInit() {
        this._fetchGoodiesService.getGoodies().subscribe( data => {
            this.res = data
            this.goodies = this.res.posts
            console.log("this goodies", data) 
        });
    }

}