Angular 2-订阅不是函数错误

时间:2018-03-17 21:47:06

标签: angular angular2-services

我正在尝试从服务订阅,它构建没有错误,但在浏览器中查看时,我收到错误“this.myService.getAll不是函数”。

服务:

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,
  }],

任何想法我做错了什么?

2 个答案:

答案 0 :(得分:2)

您必须将提供商声明为:

providers: [
    MyServiceService
]

因为您使用HashLocationStrategy课程代替服务类,HashLocationStrategy没有getAll功能。

另一件事是将您的服务注入私人:

constructor(private myService:MyServiceService)

并调用您从ngOnInit

添加的subscribe功能
ngOnInit() {
    this.subscribe();
}

答案 1 :(得分:1)

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

        original_df <- as.data.frame(file)
        data8 <- original_df [(original_df [785,] == 8),]

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

public subscribetoGetAll(...;