Search code examples
angularangular2-services

Angular 2- Subscribe is not a function error


I am trying to subscribe from a service, it builds without error but I get the error "this.myService.getAll is not a function" when viewing in the browser.

Service:

import { Injectable } from '@angular/core';
import { Http } from "@angular/http";


@Injectable()

export class MyServiceService {

  url:string;

  constructor(private http:Http) {
    this.url = "http://127.0.0.1:8000/scrumboard";
  }

  public getAll(): any {
    let result = this.http.get(this.url+"/lists");
    return result;
  }
}

Component:

import { Component, OnInit } from '@angular/core';

import { MyServiceService } from '../my-service.service';
import { Response } from '@angular/http';


@Component({
  selector: 'app-dashboard',
  templateUrl: './full-layout.component.html'
})
export class FullLayoutComponent {

  public disabled: boolean = false;
  public status: {isopen: boolean} = {isopen: false};

  public toggled(open: boolean): void {
    console.log('Dropdown is now: ', open);
  }

  public toggleDropdown($event: MouseEvent): void {
    $event.preventDefault();
    $event.stopPropagation();
    this.status.isopen = !this.status.isopen;
  }

  constructor(public myService:MyServiceService) {

  }
  public subscribe() {
    this.myService.getAll().subscribe(
      (data: Response) => console.log(data)
    );
  }
}

Finally the app.module.ts:

providers: [{
    provide: MyServiceService,
    useClass: HashLocationStrategy,
  }],

Any ideas what I am doing wrong?


Solution

  • You have to declare your provider as:

    providers: [
        MyServiceService
    ]
    

    Because you are using HashLocationStrategy class in place of your service class, and HashLocationStrategy don't have getAll function.

    Another thing is to inject your service as private:

    constructor(private myService:MyServiceService)
    

    And call that subscribe function you added from ngOnInit

    ngOnInit() {
        this.subscribe();
    }