angular – 订阅不是函数错误

前端之家收集整理的这篇文章主要介绍了angular – 订阅不是函数错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图从服务订阅一个observable,它构建没有错误,但我在浏览器中查看时得到错误“this.service.getBanners(…).subscribe不是一个函数”.

服务:

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);
    }
}

我有什么想法我做错了吗?

@H_502_12@
你应该返回一个observable,而不是你返回一个数组,
getBanners(): Observable<any[]> {
    return Observable.of(this.banners);
}
原文链接:https://www.f2er.com/angularjs/140900.html

猜你在找的Angularjs相关文章