gpt4 book ai didi

angular - 'Observable<英雄[] >' is not assignable to type ' 英雄[]'

转载 作者:行者123 更新时间:2023-12-01 22:08:15 26 4
gpt4 key购买 nike

我正在关注 Angular 的 Tour of Heroes Tutorial我现在正在尝试将 observables 集成到我的项目中。将我的 hero.service.ts 文件更改为如下所示后

import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
import { Observable } from 'rxjs/Rx';
import { of } from 'rxjs/observable/of';

@Injectable()
export class HeroService {

constructor() { }

getHeroes(): Observable<Hero[]> {
return of(HEROES);
}
}

我没有收到以下错误

ERROR in src/app/heroes/heroes.component.ts(27,5): error TS2322: Type 'Observable' is not assignable to type 'Hero[]'. Property 'includes' is missing in type 'Observable'.

我不太确定我在这里做错了什么。我的英雄定义中并没有真正的“包含”属性。那个类看起来像这样

export class Hero {
id: number;
name: string;
}

这是一个link to my project虽然我无法让它在堆栈 Blitz 中运行

我会在这里列出完整的代码

英雄.component.ts

import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';
import { HeroService } from '../hero.service';

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

constructor(private heroService: HeroService) { }

selectedHero: Hero;

heroes: Hero[];

ngOnInit() {
this.getHeroes();
}

onSelect(hero: Hero): void {
this.selectedHero = hero;
}

getHeroes(): void {
this.heroes = this.heroService.getHeroes();
}




}

英雄.service.ts

import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
import { Observable } from 'rxjs/Rx';
import { of } from 'rxjs/observable/of';

@Injectable()
export class HeroService {

constructor() { }

getHeroes(): Observable<Hero[]> {
return of(HEROES);
}
}

英雄.ts

export class Hero {
id: number;
name: string;
}

模拟英雄.ts

import { Hero } from './hero';

export const HEROES: Hero[] = [
{ id: 11, name: 'Mr. Nice' },
{ id: 12, name: 'Narco' },
{ id: 13, name: 'Bombasto' },
{ id: 14, name: 'Celeritas' },
{ id: 15, name: 'Magneta' },
{ id: 16, name: 'RubberMan' },
{ id: 17, name: 'Dynama' },
{ id: 18, name: 'Dr IQ' },
{ id: 19, name: 'Magma' },
{ id: 20, name: 'Tornado' }
];

最佳答案

问题是:

  getHeroes(): void {
this.heroes = this.heroService.getHeroes();
}

正如错误告诉您的那样,this.heroes类型为 Hero[] (因此,一个 Hero 元素的数组),而 this.heroService.getHeroes();返回一个类型为 Observable<Hero[]>observable .

由于您正在使用可观察对象,因此您必须正确订阅它,如下所示:

getHeroes(): void {
this.heroService.getHeroes().subscribe(result => this.heroes = result);
}

关于angular - 'Observable<英雄[] >' is not assignable to type ' 英雄[]',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50215571/

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