【问题标题】:TypeError: _this. is not a function类型错误:_this。不是函数
【发布时间】:2018-04-11 00:37:22
【问题描述】:

当我尝试从另一个服务函数调用的 subscribe() 方法中调用一个服务函数时,我遇到了一个奇怪的错误。 TypeError 状态:

TypeError: _this.fileloaderService.downloadFile is not a function

我有两项服务,一项用于获取剧集,另一项用于加载文件内容。我将它们都导入并将它们包含在我的 EpisodesComponent 构造函数中,如下所示:

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

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

然后我得到我的剧集,当它们被返回时,我尝试从我的剧集对象中的一个字段 url 加载一个文件:

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

但是,在控制台运行时,它会抱怨 downloadFile() 方法不存在。但是它编译正确,你可以看到它确实存在 在下面的服务中。

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

似乎它在抱怨它不存在/未实例化或其他什么,但我创建和包含这两个服务的方式是相同的。

有什么想法吗? (我是 Typescript 的新手,所以请放轻松!)提前谢谢...

EDIT 1:我正在使用 ng serve --open 运行它 我已经包括:

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

在 getEpisodes().subscribe() 函数中,它会输出:

fileloaderService: {}

编辑 2:我还向 app.module.ts 提供者添加了该服务,如下所示:

providers: [EpisodeService, FileloaderService],

编辑 3:我在此处创建了应用程序的堆栈闪电战:

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

不幸的是,我目前正在努力让 in-memory-web-api 的东西正常工作,但你应该能够看到我所拥有的一切(我认为)

【问题讨论】:

  • 你的代码看起来不错,你能把它发布到 stackblitz 上并给我们链接吗?我将负责为您模拟 HTTP 调用,并尝试找出您的问题。
  • console.log(this.fileloaderService) 显示什么?另外,FileloaderService 是一个类还是一个接口?您是否尝试在开发模式和/或生产模式下运行您的应用程序(ng build -prod)?
  • 当我将它记录到控制台时,它会给出:fileloaderService: [object Object]。当我 JSON.stringify 它时,它给出: fileloaderService: {}
  • 我正在运行应用程序:ng server --open
  • 您确实将您的服务添加到了提供商,对吧?

标签: angular typescript angular-services


【解决方案1】:

你可以这样试试

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

【讨论】:

  • 你能提供你的pluker链接吗
【解决方案2】:

这似乎是由于 downloadFile() 方法中的 http.get() 格式不正确,并且除了我尝试使用的 RequestOptions 对象之外没有。

我认为这是由于将已弃用的 @angular/http 库与较新的 @angular/common/http 一起使用造成的

抱歉耽误大家时间

【讨论】:

    猜你喜欢
    • 2018-05-29
    • 1970-01-01
    • 2016-02-26
    • 2013-04-01
    • 2016-03-06
    • 2018-04-28
    • 2019-02-14
    • 2021-10-02
    相关资源
    最近更新 更多