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?
Subscribe() is a method in Angular that connects the observer to observable events. Whenever any change is made in these observable, a code is executed and observes the results or changes using the subscribe method. Subscribe() is a method from the rxjs library, used internally by Angular.
map instead of . subscribe. Later is mainly used if you want the response updated to the DOM.
Remember, observables are lazy. If you don't subscribe nothing is going to happen. It's good to know that when you subscribe to an observer, each call of subscribe() will trigger it's own independent execution for that given observer. Subscribe calls are not shared among multiple subscribers to the same observable.
Normally Subscription means an arrangement to receive something. Similarly, in Angular applications Observables will be connected to observers and whenever they observe a new value or change in data, they will execute code with the help of Subscription and all the subscribed components will receive the updated outcome.
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); }
Reference
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With