Angular Subscribe()返回未定义

时间:2018-06-23 13:41:07

标签: angular http service subscribe

如果控制台向我显示以下内容,如何解决subcribe()对我的app.component的问题:错误TypeError:无法读取未定义的属性“ subscribe” 在AppComponent.push ../ src / app / app.component.ts.AppComponent.ngOnInit

数据服务:

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

   import { Injectable } from '@angular/core';
   import { Observable, Subject, ReplaySubject } from 'rxjs';
   import { from, of, range } from 'rxjs/create';
   import { map, filter, switchMap } from 'rxjs/operators';


 @Injectable({
    providedIn: 'root'
    })


export class DataService {

  constructor(private http: Http) { }

  fetchData(){
    this.http.get('assets/ninjas.json').pipe(
     map((res) => return res.json()))}}

应用组件:

import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'app';
  ninjas = [];

  constructor(private newService: DataService){ }

  ngOnInit(){
   this.newService.fetchData().subscribe(
    (data) => this.ninjas = data;
   );
  }
 }

2 个答案:

答案 0 :(得分:1)

返回服务中的可观察物,

 fetchData(){
    return this.http.get('assets/ninjas.json').pipe(
     map((res) => return res.json()))}}

答案 1 :(得分:0)

只需删除“管道”即可,您不需要它:

    let min = (a,b) => 
      if (a < b) {
        return a;
      }
      else if (b < a) {
        return b;
      }
      else {
        console.log("error");
      };