Angular2:类型“订阅”不能分配给

时间:2016-07-09 18:34:47

标签: javascript http angular observable

我创建了一个非常小的应用程序,用于从json文件中获取国家/地区并将其绑定到下拉列表。

  

countries.json

export class Country {
    id: number;
    name: string;
}
  

factory.service.ts

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

import { Country } from './shared/country';

@Injectable()
export class FactoryService {
    private countryUrl = "app/data/countries.json";

    constructor(private http: Http) {

    }

    getCountry(): Observable<any> {
        return this.http.get(this.countryUrl)
            .map(this.extractData)
            .do(data => console.log("get Countries from json: " + JSON.stringify(data)))
            .catch(this.handleError);
    }

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

    private handleError(error: Response) {
        console.log(error);
        return Observable.throw(error.json().error || "500 internal server error");
    }
}
  

工厂form.component.ts

import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';

import { Factory } from './factory';
import { Country } from './shared/country';
import { FactoryService } from './factory.service';

@Component({
    moduleId: module.id,
    selector: 'factory-form',
    templateUrl: './factory-form.component.html',
    styleUrls: ['./factory-form.component.css'],
    providers: [FactoryService]
})
export class FactoryFormComponent implements OnInit{

    private model: Factory;
    countries: Country[];
    factoryStatuses;
    productTypes;
    risks;
    private errorMessage: string;
    private submitted = false;

    constructor(private factoryService: FactoryService) {

    }

    ngOnInit(): void {
        this.countries = this.factoryService.getCountry()
            .subscribe(countries => this.countries = countries,
            error => this.errorMessage = error);
    }

    onSubmit(): void {
        this.submitted = true;
    }}
  

factory-form.component.html代码段

<div class="col-lg-3">
            <select class="form-control" name="Country">
                <option *ngFor="let country of countries" [value]="country.id">{{country.name}}</option>
            </select>
        </div>

我收到运行时错误如下:

  

错误:Typescript发现以下错误:
  C:/Projects/ethical_resourcing/src/Ethos.Client/tmp/broccoli_type_script_compiler-input_base_path-kviWq7F3.tmp/0/src/app/factory/factory-form.component.ts   (30,9):“订阅”类型不能分配给“国家[]”类型   “订阅”类型中缺少“属性长度”   C:/Projects/ethical_resourcing/src/Ethos.Client/tmp/broccoli_type_script_compiler-input_base_path-kviWq7F3.tmp/0/src/app/factory/shared/country.ts   (2,15):';'预期。       在BroccoliTypeScriptCompiler._doIncrementalBuild(C:\ Projects \ ethical_resourcing \ src \ Ethos.Client \ node_modules \ angular-cli \ lib \ broccoli \ broccoli-typescript.js:120:19)       在BroccoliTypeScriptCompiler.build(C:\ Projects \ ethical_resourcing \ src \ Ethos.Client \ node_modules \ angular-cli \ lib \ broccoli \ broccoli-typescript.js:43:10)       在C:\ Projects \ ethical_resourcing \ src \ Ethos.Client \ node_modules \ angular-cli \ node_modules \ broccoli-caching-writer \ index.js:152:21       在lib $ rsvp $$ internal $$ tryCatch(C:\ Projects \ ethical_resourcing \ src \ Ethos.Client \ node_modules \ angular-cli \ node_modules \ rsvp \ dist \ rsvp.js:1036:16)       在lib $ rsvp $$ internal $$ invokeCallback(C:\ Projects \ ethical_resourcing \ src \ Ethos.Client \ node_modules \ angular-cli \ node_modules \ rsvp \ dist \ rsvp.js:1048:17)       在lib $ rsvp $$ internal $$ publish(C:\ Projects \ ethical_resourcing \ src \ Ethos.Client \ node_modules \ angular-cli \ node_modules \ rsvp \ dist \ rsvp.js:1019:11)       在lib $ rsvp $ asap $$ flush(C:\ Projects \ ethical_resourcing \ src \ Ethos.Client \ node_modules \ angular-cli \ node_modules \ rsvp \ dist \ rsvp.js:1198:9)       at nextTickCallbackWith0Args(node.js:420:9)       at process._tickCallback(node.js:349:13)

现在,如果我将可观察国家的类型更改为任何,则我会收到以下错误

  

ORIGINAL EXCEPTION:无法找到'object'类型的不同支持对象'[object Object]'。 NgFor仅支持绑定到Iterables   例如Arrays。

1 个答案:

答案 0 :(得分:12)

是的,类型必须是Observable,您需要使用异步管道让ngFor满意:

*ngFor="let country of countries | async"

或者另一种选择是保留Country[]类型,然后订阅并将countries分配给数组:

this.factoryService.getCountry() // note, removed this.countries = 
    .subscribe(
        countries => this.countries = countries,
        error => this.errorMessage = error
    );