Reputation: 353
Service module:
import { Observable } from 'rxjs/Rx';
import { Http,Response} from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/Map';
@Injectable()
export class VideoService {
private geturl = '/api/videos';
constructor(private _http:Http) { }
getvideos() {
return this._http.get(this.geturl).map((response:Response) => {
response.json()
});
}
}
Here is where the subscribe method is showing this error:
import { VideoService } from '../video.service';
import { Component, OnInit } from '@angular/core';
import { Video } from '../video';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'app-videocenter',
templateUrl: './videocenter.component.html',
styleUrls: ['./videocenter.component.css']
})
export class VideocenterComponent implements OnInit {
videos: any;
onselectvideo: Video;
switch: boolean = false
constructor(private videoserv: VideoService) {
//console.log(this.videos);
}
onselect(vid: any) {
this.switch = true;
this.onselectvideo = vid;
console.log(vid);
}
ngOnInit() {
this.videos = this.videoserv.getvideos .subscribe((response) => {
this.videos = response;
});
}
}
I have the service in which I have to call my API to return other API's. When I am going to subscribe to the method in the other class where I am calling that service method getvideos(), then it's showing this error that the property "subscribe " does not exist on type ()=> observable.
Upvotes: 31
Views: 132876
Reputation: 31
this.service.method().subscribe(response)...
Whenever this.service
is typed and auto suggestion appears, in suggestion , method name is suggested and once suggestion is accepted, it takes up only method name without parenthesis().
this.service.method.subscribe()..
=> Will give error
this.service.method().subscibe()..
=> Correct
Upvotes: 3
Reputation: 333
But if you also want to use your service method getvideos() in another place of your application (component, pipe...etc)
You can do .pipe(map()) instead of .subscribe()
ngOnInit() {
this.videoserv.getvideos().pipe(map(response) => {
this.videos = response
}));
}
And then use .subscribe in the place where you want to have your videos
this.videoserv.getvideos().subscribe(response) => {
this.videos2 = response
});
Upvotes: 1
Reputation: 40534
You are not calling the getVideos
method. You are calling subscribe
on the function reference of getVideos
and not the returned value. Call subscribe
after you call getVideos()
:
ngOnInit() {
this.videoserv.getvideos().subscribe((response) => {
this.videos = response
});
}
Upvotes: 120
Reputation: 71
ngOnInit() {
this.videoserv.getvideos().subscribe((response) => {
this.videos = response
});
}
You should be calling the getvideos()
method on the videoserv
service.
You were missing the ()
, getvideos
is a method not a property.
Upvotes: 6