Search code examples
angulartypescriptangular-services

TypeError: _this. is not a function


I am getting a strange error when I try and call a service function from within the subscribe() method of another service function call. The TypeError states:

TypeError: _this.fileloaderService.downloadFile is not a function

I have two services, one to get some episodes, and another to load the contents of a file. I import them both and include them in my EpisodesComponent constructor like so:

import { EpisodeService } from '../episode.service';
import { FileloaderService } from '../fileloader.service';

constructor(private episodeService: EpisodeService,
  private fileloaderService: FileloaderService) { }

Then I get my episodes, and when they are returned I try to load a file from a url that is a field in my episode object:

getEpisodes(): void {
  this.episodeService.getEpisodes().subscribe(episodes => {
    this.episodes = episodes;
    for (let i of this.episodes) {
      this.fileloaderService.downloadFile(i.fileUrl).subscribe(file => {
        i['file'] = file;
      });
    }
  });
}

However, in the console when it is run it complains about the downloadFile() method not existing. However it compiles correctly and you can see it does exist in the service below.

@Injectable()
export class FileloaderService {

  constructor(private http: HttpClient) { }

  downloadFile(fileUrl): Observable<Text> {
    let options = new RequestOptions({responseType: ResponseContentType.Text});
    return this.http.get(fileUrl, options)
      .catch(this.handleError('downloadFile'));
  }

It seems like it is complaining it doesn't exist/isn't instantiated or something, but the way I've created and included the two services is identical.

Any ideas? (I'm completely new to Typescript so please go easy on me!) Thanks in advance...

EDIT 1: I am running this using ng serve --open I have included:

console.log("fileloaderService:" + JSON.stringify(this.fileloaderService));

inside the getEpisodes().subscribe() function and it outputs this:

fileloaderService: {}

EDIT 2: I have also added the service to the app.module.ts providers like this:

providers: [EpisodeService, FileloaderService],

EDIT 3: I've created a stackblitz of the app simplified here:

https://stackblitz.com/edit/angular-sazw43

Unfortunately I'm struggling to get the in-memory-web-api stuff to work correctly at the moment but you should be able to see everything as I have it (I think)


Solution

  • It seems this was caused by the http.get() in the downloadFile() method was not properly formatted and does not except a RequestOptions object like I was trying to use.

    This was caused i think by using the deprecated @angular/http library with the newer @angular/common/http

    Sorry for wasting everybodies time