输入'Observable<any>'不可分配到类型“[]" [英] Type &#39;Observable&lt;any&gt;&#39; is not assignable to type &#39;[]&#39;

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

问题描述

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

这是我的代码:

product-maintenance.component.ts从@angular/core"导入{组件,OnInit};从'../../_services/product-maintenance.service'导入{ProductMaintenanceService};从'../../../data/const'导入{ ModuleConst };从'./product-types'导入{产品};从'./products'导入{产品};@零件({选择器:应用程序产品维护",templateUrl: './product-maintenance.component.html',styleUrls: ['./product-maintenance.component.css']})导出类 ProductMaintenanceComponent 实现 OnInit {selectedProduct: Product = new Product(0, '保险');产品:产品[];产品列表:产品[];构造函数(私人产品服务:产品维护服务){}ngOnInit() {//下拉列表this.products = this.productService.getProductTypeList();}//使用 onSelect 方法填充数据onSelect(typeid) {this.productList = this.productService.getProducts().filter((item)=>item.ptypeid == typeid);}}

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

导出类产品{构造函数(公共 ptypeid:数字,公共名称:字符串) { }}

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

出口类产品{构造函数(公共 ID:号码,公共 ptypeid:数字,公共名称:字符串,公共货币:字符串,公共状态:字符串,公共风险评级:数字,公共客户端段:字符串,公共 aiStatus:字符串,公共溢价类型:字符串,公共任期:数量) { }}

product-maintenance.service.ts:

import { Injectable, Inject } from '@angular/core';从@angular/http"导入 { Http, Headers, RequestOptions, Response };从 'rxjs/Rx' 导入 { Observable };导入 'rxjs/add/operator/map';导入 'rxjs/add/operator/filter';从 '../app.config' 导入 { APP_CONFIG, IAppConfig };从'./products'导入{产品};从'./product-types'导入{产品};@Injectable()导出类 ProductMaintenanceService {结果:数组<对象>;构造函数(@Inject(APP_CONFIG) 私有配置:IAppConfig,私有 http: Http) { }private productURL = 'data/productList.json';//获取产品列表getProducts() : Observable{//...使用获取请求返回 this.http.get(this.productURL)//...并在响应上调用 .json() 以返回数据.map((响应:响应) => {控制台日志(响应);返回 response.json();});}获取产品类型列表(){返回 [新产品(1,'单位信托'),新产品(2,'保险'),新产品(3, '结构性存款'),新产品(4,'债券'),新产品(5,'DCI'),新产品(6,'SP')];}}

product-maintenance.component.html:

<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>

productList.json:

<预><代码>[{ptypeid":1,身份证":1,"name": "单位信托 1","货币": "新加坡元","状态": "活动",风险评级":1,"clientSegment": "零售/高级","aiStatus": "否","premiumType": "普通保费",任期":5},{ptypeid":2,身份证":2,"name": "Unit Trust 2","货币": "新加坡元","状态": "活动",风险评级":3,"clientSegment": "零售/高级","aiStatus": "否","premiumType": "单次/一次性溢价",任期":10}]

如果我将我的 getProducts() 定义为 getProductTypeList() 那么它会在我的视图中完美地填充数据(如果我从下拉列表中选择 Unit trust 那么它应填充相关数据).但是,如果我将其用作 api url,则会出现以下错误:

输入'Observable'不可分配到类型产品[]".'Observable'

类型中缺少属性length"

我不明白如何解决这个错误.任何人都可以帮我解决这个问题.提前致谢.

解决方案

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

数组

onSelect(typeid) {this.productService.getProducts().管道(filter((item)=>item.ptypeid == typeid)).subscribe((产品) => {this.productList = 产品;});}

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.

Here is my code:

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 (used for to populate drop down list):

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

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
      }
]

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>'

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

解决方案

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()
    .pipe(
        filter((item)=>item.ptypeid == typeid)
    )
    .subscribe((products) => {
       this.productList = products;
    });
}

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

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