Angular 2-订阅不是函数错误

Angular 2- Subscribe is not a function error

我正在尝试从服务订阅,它构建时没有错误,但在浏览器中查看时出现错误 "this.myService.getAll is not a function"。

服务:

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

组件:

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

最后 app.module.ts:

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

知道我做错了什么吗?

将方法命名为 subscribe() 这样的方法是错误的决定,因为它可能会使您和其他开发人员混淆,最好将其命名为:

public subscribetoGetAll(...;

您的解决方案是在构造函数或 ngOnInit 中调用此方法(最好在 ngOnInit 中调用):

export class FullLayoutComponent, OnInit {

  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(private myService:MyServiceService) {

  }

  ngOnInit() { // ngOnInit added
    this.subscribetoGetAll();  // <-- here you calling your method
  }


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

您必须将您的提供商声明为:

providers: [
    MyServiceService
]

因为您正在使用 HashLocationStrategy class 代替您的服务 class,并且 HashLocationStrategy 没有 getAll 功能。

另一件事是将您的服务作为私有注入:

constructor(private myService:MyServiceService)

然后调用您从 ngOnInit

添加的 subscribe 函数
ngOnInit() {
    this.subscribe();
}