Reputation: 4362
I am trying to subscribe to an observable from a service, it builds without error but I get the error "this.service.getBanners(...).subscribe is not a function" when viewing in the browser.
Service:
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;
}
}
Component:
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);
}
}
Any ideas what I am doing wrong?
Upvotes: 26
Views: 97300
Reputation: 222722
You should return an observable , instead you are returning an array:
For Angular <= 5.x.x
getBanners(): Observable<any[]> {
return Observable.of(this.banners);
}
For Angular >= 6.x.x
getBanners(): Observable<any[]> {
return of(this.banners);
}
Upvotes: 41
Reputation: 12376
A couple of things to fix.
You declare that your function getBanners() returns an Observable, but you return an array. So change your return statement to
return Observable.from(this.banners);
You'll also need to add this:
import 'rxjs/add/observable/from';
This is bad practice and will include the entire rxjs library into your code:
import { Observable } from 'rxjs';
Import only what you need. Replace the above with
import { Observable } from 'rxjs/Observable';
Upvotes: 6