【发布时间】:2018-12-03 01:17:55
【问题描述】:
我的 Angular 应用程序从 REST API 检索状态数据并显示在网页上。我有state component 调用state service,然后使用httpClient.get() 方法调用后端。当我将参数从组件传递到服务时,我在组件订阅方法上看到 HttpEvent<Observable<State[]>>' is not assignable to type 'Observable<State[]> 错误(如下所示)。当我运行项目时,代码无法编译并抛出以下错误。
错误:
Date: 2018-12-03T01:18:53.456Z
ERROR in src/app/state/state.component.ts(28,17): error TS2322: Type 'HttpEvent<Observable<State[]>>' is not assignable to type 'Observable<State[]>'.
Hash: 1d6c67e65c9ef90f7a15
Time: 4054ms
chunk {main} main.js, main.js.map (main) 1.88 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 92.4 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.08 kB [entry] [rendered]
Type 'HttpProgressEvent' is not assignable to type 'Observable<State[]>'.
chunk {styles} styles.js, styles.js.map (styles) 16.3 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 322 kB [initial] [rendered]
Property '_isScalar' is missing in type 'HttpProgressEvent'.
ℹ 「wdm」: Failed to compile.
我在 WebStorm IDE 上运行 Angular 7.1.0 项目。代码上传到Github repository供参考。
state.component.ts
import {Component, OnInit} from '@angular/core';
import {Observable} from 'rxjs';
import {State} from './model/state';
import {HttpHeaders} from '@angular/common/http';
import {StateService} from './services/state.service';
@Component( {
selector: 'app-state',
templateUrl: './state.component.html',
styleUrls: ['./state.component.css']
} )
export class StateComponent implements OnInit
{
statesObservable: Observable<State[]>;
constructor(private stateService: StateService) {}
ngOnInit()
{
this.getStates();
}
getStates()
{
const url='http://localhost:8080/api/v2/state/list';
const httpOptions={headers: new HttpHeaders( {'Content-Type': 'application/json'} )};
this.stateService.getStates(url,httpOptions).subscribe(
data => { this.statesObservable=data; },
err => console.error( err ),
() => console.log( 'States retrieved from backend' ) );
return this.statesObservable;
}
statesDataAvailable(): boolean
{
return this.statesObservable!==undefined;
}
}
state.service.ts
import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Observable} from 'rxjs';
import {State} from '../model/state';
@Injectable({
providedIn: 'root'
})
export class StateService
{
constructor(private httpClient:HttpClient) { }
getStates(url,httpOptions)
{
return this.httpClient.get<State[]>(url,httpOptions);
}
}
【问题讨论】:
-
发布什么是getStates,发布代码而不是图片
-
@Sajeetharan 用代码更新了帖子
标签: angular angular-httpclient angular7