Angular 4错误:类型'()=> any’中缺少属性’includes’

前端之家收集整理的这篇文章主要介绍了Angular 4错误:类型'()=> any’中缺少属性’includes’前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在使用angular 4和observable时遇到错误.

/Users//backend/src/app/app.component.ts(15,55):输入'()=>任何’不能分配给’State []’.
/Users//backend/src/app/app.component.ts(15,55):输入'()=>任何’不能分配给’State []’.
‘()=>类型中缺少属性’includes’任何’.

我究竟做错了什么

我的模特

export class State {
  id: number;
  state: string;
  code: string;
}

我的服务

import { Injectable } from '@angular/core';
import { Http,Response } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/toPromise';

import {environment} from '../../../environments/environment';

@Injectable()

export class StateService {
  private baseUrl: string = environment.baseUrl;

  constructor( private http: Http) {}

  /**
   * Get all States
   */
  GetStates() {
   return this.http.get(this.baseUrl + 'v1/states')
      .map((res: Response) => res.json);
     // .do( data => console.log(data));
  }
}

我的组件

import { Component,OnInit } from '@angular/core';
import {StateService} from './shared/services/state.service';
import {State} from './shared/models/state';

@Component({
  selector: 'app-root',templateUrl: './app.component.html',styles: []
})
export class AppComponent implements OnInit {
   states: State[] ;
  constructor(private stateService: StateService) {}

  ngOnInit() {
    this.stateService.GetStates().subscribe(states => this.states = states );
  }
}

App.Module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import 'rxjs/add/operator/map';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { StateService } from './shared/services/state.service';
@NgModule({
  declarations: [
    AppComponent
  ],imports: [
    BrowserModule,FormsModule,HttpModule,AppRoutingModule
  ],providers: [
    StateService
  ],bootstrap: [AppComponent]
})
export class AppModule { }
有两个问题.

首先,您不是在调用json响应,而只是引用该方法.您需要将res.json更改为res.json():

.map((res: Response) => res.json());

其次,您没有声明订阅结果的类型.您应该明确指定结果的类型:

this.stateService.GetStates().subscribe((states: State[]) => this.states = states);

由于您订阅的参数是any类型,除非您像上面一样预先指定类型,或者在赋值之前将其强制转换,否则typescript编译器会告诉您类型无效.

原文链接:https://www.f2er.com/angularjs/141555.html

猜你在找的Angularjs相关文章