输入"Observable< any>"不可分配给类型"[]" [英] Type 'Observable<any>' is not assignable to type '[]'

查看:80
本文介绍了输入"Observable< any>"不可分配给类型"[]"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular2/TypeScript中还很陌生,所以如果我犯了一些愚蠢的错误,请原谅.我想做的是从选择"下拉列表中,我使用服务填充数据,该服务将返回一个JSON数组.

I am pretty new in Angular2/TypeScript so please excuse me if I am doing some stupid mistake. What I am trying to do is from Select drop down I am populating the data using service which is returning me a JSON array.

这是我的代码:

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(用于填充下拉列表):

product-type.ts (used for to populate drop down list):

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

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

products.ts (used for to populate data from service):

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网址,则会出现以下错误:

If I define my getProducts() as getProductTypeList() then it's perfectly populating the data in my view (Where if I select Unit trust from the drop down then it should populate relevant data). But if I use as api url instead it's giving me below error:

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

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

我不知道如何解决此错误.谁能帮我这个忙.预先感谢.

I don't understand how to resolve this error. Can anyone please help me in this. Thanks in advance.

推荐答案

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

productList should be Product[] not Observable<any>. So assign productList value from getProducts subscribe method, where you will retrieve array of Product

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

这篇关于输入"Observable&lt; any&gt;"不可分配给类型"[]"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆