角度6:服务未定义

时间:2018-09-15 19:02:12

标签: angular

我第一次使用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文件的方法是错误的,但这不是我得到的错误。

这是怎么回事,我该如何解决?

1 个答案:

答案 0 :(得分:3)

有一段时间,该错误没有任何意义,但我只是查看了文档,却忘记了将HttpClientModule导入app.module.ts中。

将其添加到其中之后,它已修复,并且可以立即工作。

相关问题