Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6: Service is undefined

Tags:

angular

I'm using Angular for the first time and I'm trying to get a service running so I can get the contents of the file. I followed to heroes tutorial exactly where they explain how to do it and I did in the exact same way, but for some reason it doesn't work.

I get an error saying ERROR TypeError: "this.fileService is undefined", and I'm not sure what the issue is.

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

I know the method I return the HTTP file is wrong, but that's not the error I'm getting.

What's going on and how can I fix it?

like image 752
stepper Avatar asked Sep 15 '18 19:09

stepper


1 Answers

So for a while the error didn't make any sense, but I just looked over the documentation and forgot to import HttpClientModule in app.module.ts.

After adding it to that, it was fixed and it worked immediately.

like image 53
stepper Avatar answered Sep 22 '22 15:09

stepper