gpt4 book ai didi

angular - 订阅不是函数错误

转载 作者:太空狗 更新时间:2023-10-29 17:05:53 25 4
gpt4 key购买 nike

我正在尝试订阅来自服务的可观察对象,它构建时没有错误,但在浏览器中查看时出现错误“this.service.getBanners(...).subscribe is not a function”。

服务:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable()

export class BannerService {

banners: any = ['1','2','3'];

constructor(
) {}

getBanners(): Observable<any[]> {
return this.banners;
}

setBanners(banners: any[]): void {
this.banners = banners;
}

}

组件:

import { Component, ViewEncapsulation, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { BannerService } from './../banner/banner.service';

@Component({
selector: '.banner',
templateUrl: './banner.component.html',
styleUrls: ['./banner.component.sass'],
encapsulation: ViewEncapsulation.None
})

export class BannerComponent implements OnInit {

banners: any[];

constructor(private bannerService: BannerService){

}

ngOnInit() {
this.bannerService.getBanners().subscribe(banners => this.banners = banners);
}
}

知道我做错了什么吗?

最佳答案

您应该返回一个 observable ,而不是返回一个数组:

对于 Angular <= 5.x.x

getBanners(): Observable<any[]> {
return Observable.of(this.banners);
}

对于 Angular >= 6.x.x

getBanners(): Observable<any[]> {
return of(this.banners);
}

Reference

关于angular - 订阅不是函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45698036/

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