gpt4 book ai didi

angular - Angular 11 错误 TS2322 : Type 'Observable<>

转载 作者:行者123 更新时间:2023-12-04 03:38:38 24 4
gpt4 key购买 nike

我是 Angular 世界的新手,我遇到了这个错误,但我不知道如何修复它

[0] Error: src/app/components/sites-escalade/sites-escalade.component.ts:23:5 - error TS2322: Type 'Observable<AppDataState<SiteEscalade[]> | { dataState: DataStateEnum; } | { dataState: DataStateEnum; errorMessage: any; }>' is not
assignable to type 'Observable<AppDataState<SiteEscalade[]>>'.
[0] Type 'AppDataState<SiteEscalade[]> | { dataState: DataStateEnum; } | { dataState: DataStateEnum; errorMessage: any; }' is not assignable to type 'AppDataState<SiteEscalade[]>'.
[0] Type '{ dataState: DataStateEnum; }' has no properties in common with type 'AppDataState<SiteEscalade[]>'.


这是我的代码“枚举和接口(interface)”:

enter image description here

这是我的 ts 类:

import { Component, OnInit } from '@angular/core';
import {SitesEscaladeService} from '../../services/sites-escalade.service';
import {SiteEscalade} from '../../model/site-escalade.model';
import {Observable, of} from 'rxjs';
import {catchError, map, startWith} from 'rxjs/operators';
import {AppDataState, DataStateEnum} from '../../state/site-escalade.state';

@Component({
selector: 'app-sites-escalade',
templateUrl: './sites-escalade.component.html',
styleUrls: ['./sites-escalade.component.css']
})
export class SitesEscaladeComponent implements OnInit {

sitesEscalade$:Observable<AppDataState<SiteEscalade[]>> |null=null;

constructor(private sitesEscaladeService:SitesEscaladeService) { }

ngOnInit(): void {
}

onGetAllSitesEscalade() {
this.sitesEscalade$=
this.sitesEscaladeService.getAllSitesEscalade().
pipe(
map((data)=>({dataState:DataStateEnum.LOADED, data:data})),
startWith({dataState:DataStateEnum.LOADING}),
catchError(err=>of({dataState:DataStateEnum.ERROR, errorMessage:err.message}))
);
}

}

谢谢你的帮助

最佳答案

仔细查看错误信息:

Type 'Observable<AppDataState<SiteEscalade[]> | { dataState: DataStateEnum; } | { dataState: DataStateEnum; errorMessage: any; }>' is not
assignable to type 'Observable<AppDataState<SiteEscalade[]>>'

所以你的 onGetAllSitesEscalade()方法试图将某些东西分配给 this.sitesEscalade$ ( Observable<AppDataState<SiteEscalade[]>> ) 这不仅仅是 AppDataState<SiteEscalade[]> 类型的可观察对象.

map((data)=>({dataState:DataStateEnum.LOADED, data:data}))

将返回一个无类型对象,而不是 AppDataState。同样的

catchError(err=>of({dataState:DataStateEnum.ERROR, errorMessage:err.message}))

丑陋的解决方法是将所有内容都转换为 as AppDataState<SiteEscalade[]> .

https://stackblitz.com/edit/angular-ivy-islg9b

更好的方法是定义一个实现 AppDataState 的类(或者为什么不将 AppDataState 定义为类而不是接口(interface)?)

关于angular - Angular 11 错误 TS2322 : Type 'Observable<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66454742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com