类型'Observable <any>'不能分配给'[]'类型

时间:2017-01-24 04:02:20

标签: angular typescript rxjs observable

我是Angular2 / TypeScript的新手,所以如果我做了一些愚蠢的错误,请原谅。我想要做的是从Select下拉我使用服务填充数据,这将返回一个JSON数组。

这是我的代码:

product-maintenance.component.ts

import { Component, OnInit} from '@angular/core';
import { ProductMaintenanceService } from '../../_services/product-maintenance.service';
import { ModuleConst } from '../../../data/const';
import { Product } from './product-types';
import { Products } from './products';

@Component({
  selector: 'app-product-maintenance',
  templateUrl: './product-maintenance.component.html',
  styleUrls: ['./product-maintenance.component.css']
})

export class ProductMaintenanceComponent implements OnInit {
 selectedProduct: Product = new Product(0, 'Insurance');
 products: Product[];
 productList: Products[];

 constructor( private productService: ProductMaintenanceService ) {

 }

    ngOnInit() {
      // Dropdown list
      this.products = this.productService.getProductTypeList();
    }
    // Populate data using onSelect method
    onSelect(typeid) {
      this.productList = this.productService.getProducts()
        .filter((item)=>item.ptypeid == typeid);
    }
}

product-type.ts(用于填充下拉列表):

export class Product {
  constructor(
    public ptypeid: number,
    public name: string
  ) { }
}

products.ts(用于填充服务中的数据):

export class Products {
  constructor(
      public id: number,
      public ptypeid: number,
      public name: string,
      public currency: string,
      public state: string,
      public riskRating: number,
      public clientSegment: string,
      public aiStatus: string,
      public premiumType: string,
      public tenure: number
  ) { }
}

product-maintenance.service.ts

import { Injectable, Inject } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/filter';
import { APP_CONFIG, IAppConfig } from '../app.config';
import { Products } from './products';
import { Product } from './product-types';

@Injectable()
export class ProductMaintenanceService {
    result: Array<Object>;
    constructor(
        @Inject(APP_CONFIG) private config: IAppConfig,
        private http: Http
      ) { }

    private productURL = 'data/productList.json';

    // Get product list
    getProducts() : Observable<any> {
     // ...using get request
     return this.http.get(this.productURL)
        // ...and calling .json() on the response to return data
        .map((response: Response) => {
          console.log(response);
          return response.json();
        });
     }


     getProductTypeList() {
       return [
         new Product(1, 'Unit Trust'),
         new Product(2, 'Insurance'),
         new Product(3, 'Structured Deposit'),
         new Product(4, 'Bonds'),
         new Product(5, 'DCI'),
         new Product(6, 'SP')
       ];
     }
}

product-maintenance.component.html

<table>
<tr *ngFor="let item of productList">
                <td>{{ item.id }}</td>
                <td>{{ item.name }}</td>
                <td>{{ item.currency }}</td>
                <td>{{ item.state }}</td>
                <td>{{ item.riskRating }}</td>
                <td>{{ item.clientSegment }}</td>
                <td>{{ item.aiStatus }}</td>
                <td>{{ item.premiumType }}</td>
                <td>{{ item.tenure }}</td>
            </tr>
</table>

productList.json

[
      {
        "ptypeid": 1,
        "id": 1,
        "name": "Unit Trust 1",
        "currency": "SGD",
        "state": "Active",
        "riskRating": 1,
        "clientSegment": "Retail/Premier",
        "aiStatus": "No",
        "premiumType": "Regular Premium",
        "tenure": 5
      },
      {
        "ptypeid": 2,
        "id": 2,
        "name": "Unit Trust 2",
        "currency": "SGD",
        "state": "Active",
        "riskRating": 3,
        "clientSegment": "Retail/Premier",
        "aiStatus": "No",
        "premiumType": "Single/Lumpsum Premium",
        "tenure": 10
      }
]

如果我将getProducts()定义为getProductTypeList(),那么它就完全填充了我视图中的数据(如果我从下拉列表中选择单位信任,那么它应该填充相关数据)。但是,如果我使用api url而不是它给我下面的错误:

Type 'Observable<any>' is not assignable to type 'Products[]'. Property 'length' is missing in type 'Observable<any>'

我不明白如何解决此错误。任何人都可以帮助我。提前谢谢。

4 个答案:

答案 0 :(得分:6)

productList应为Product[]而不是Observable<any>。因此,从productList订阅方法中分配getProducts值,您将在其中检索Product

的数组
onSelect(typeid) {
  this.productService.getProducts()
    .filter((item)=>item.ptypeid == typeid)
    .subscribe((products) => {
       this.productList = products;
    });
}

答案 1 :(得分:4)

将方法getProducts方法更改为

getProducts() : Observable<any> {
     // ...using get request
     let response = this.http.get(this.productURL)
        // ...and calling .json() on the response to return data
        .map((response: Response) => response.json());
    return response;
 }

答案 2 :(得分:3)

有几个问题,首先我注意到你正在使用相对网址来获取请求。那不行。您需要拥有正确的URL,这意味着以http://..开头的内容,即使您的api在localhost上,您也需要提供完整的URL。

其次,get请求没问题,但您在组件中的调用应如下所示:

this.productService.getProducts()
  .subscribe(data => {
   this.productList = data})

由于您在请求中正在制作地图,您还需要订阅该地图,否则您将无法获得任何结果!

值得一提的是,由于这是一个异步操作,您可能希望在表中包含ngIf,以便在数据到达之前呈现视图时,您的应用不会抛出错误,所以这样做:

<table *ngIf="productList">

这应该清楚了!

或者,如果您不想订阅,可以像以前一样进行:

this.products = this.productService.getProductTypeList();

但是你必须在视图中使用async管道:

<tr *ngFor="let item of productList | async">

在这种情况下,async-pipe会为您订阅:)

答案 3 :(得分:0)

TypeScript 和 HTML 中的变量数量必须相同。

打字稿:

export class Products {
  public id: number,
  public ptypeid: number,
  public name: string,
  public currency: string,
  public state: string,
  public riskRating: number,
  public clientSegment: string,
  public aiStatus: string,
  public premiumType: string,
  public tenure: number

}

HTMH:

    <table>
  <tr *ngFor="let item of productList">
            <td>{{ item.id }}</td>
            <td>{{ item.ptypeid}}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.currency }}</td>
            <td>{{ item.state }}</td>
            <td>{{ item.riskRating }}</td>
            <td>{{ item.clientSegment }}</td>
            <td>{{ item.aiStatus }}</td>
            <td>{{ item.premiumType }}</td>
            <td>{{ item.tenure }}</td>
        </tr>