首页 > 解决方案 > Angular 6:服务未定义

问题描述

我是第一次使用 Angular,我正在尝试运行一项服务,以便获取文件的内容。我完全按照英雄教程,他们解释了如何做到这一点,我以完全相同的方式做了,但由于某种原因它不起作用。

我收到一条错误消息ERROR TypeError: "this.fileService is undefined",我不确定问题是什么。

about.component.ts

import { Component, OnInit } from '@angular/core'
import { FileService } from './../file.service'

declare var require:any;
const markdown = require('markdown').markdown;

@Component({
  selector: 'app-about',
  templateUrl: './about.component.html',
  styleUrls: ['./about.component.scss']
})
export class AboutComponent implements OnInit {

  constructor(private fileService:FileService) { }

  ngOnInit() {
    const aboutmeraw = this.fileService.readFile("./../assets/md/aboutme.md");
    this.aboutme = markdown.toHTML(aboutmeraw);
  }

  aboutme:string;

}

file.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class FileService {

  constructor(private http:HttpClient) { }

  public readFile(file:string):Observable<any> {
    return this.http.get(file);
  }
}

我知道我返回 HTTP 文件的方法是错误的,但这不是我得到的错误。

发生了什么事,我该如何解决?

标签: angular

解决方案


所以有一段时间这个错误没有任何意义,但我只是查看了文档并忘记导入HttpClientModule.app.module.ts

将其添加到其中后,它已修复并立即起作用。


推荐阅读