【问题标题】:Angular2 : Type 'Subscription' is not assignable to typeAngular2:类型“订阅”不可分配给类型
【发布时间】:2016-11-12 02:35:42
【问题描述】:

我创建了一个非常小的应用程序来从 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");
    }
}

factory-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 sn-p

<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) 在 nextTickCallbackWith0Args (node.js:420:9) 在 process._tickCallback (node.js:349:13)

现在,如果我将 Observable 和 countries 的类型更改为任何类型,那么我将得到以下错误

原始异常:找不到“object”类型的不同支持对象“[object Object]”。 NgFor 只支持绑定到 Iterables 比如数组。

【问题讨论】:

    标签: javascript http angular observable


    【解决方案1】:

    是的,类型必须是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
        );
    

    【讨论】:

    • 得到了这个异常:管道“AsyncPipe”的参数“[object Object]”无效
    • 我删除了异步管道并尝试了您的建议。瞧,它修复了错误。为什么 this.countries 给出错误?基本上我只是在关注 Pluralsight 视频,它对她有用。她使用的是测试版,但我使用的是 rc.4。我浪费了 3 个小时 :(
    • 我忘了说是你使用管道然后删除.subscribe(...)部分:this.countries = this.factoryService.getCountry().error(...)。
    猜你喜欢
    • 2019-08-01
    • 1970-01-01
    • 2019-03-27
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 2020-09-08
    • 1970-01-01
    相关资源
    最近更新 更多