Angular subscribe() 返回未定义
Angular subscribe() returning undefined
如果我的控制台显示以下内容,我该如何解决 app.component 的 subcribe() 问题:错误类型错误:无法读取 属性 'subscribe'未定义的
在 AppComponent.push../src/app/app.component.ts.AppComponent.ngOnInit
data.service:
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()))}}
app.components:
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;
);
}
}
Return 您服务中的可观察对象,
fetchData(){
return this.http.get('assets/ninjas.json').pipe(
map((res) => return res.json()))}}
只需删除 'pipe',您不需要它:
fetchData(){
return this.http.get('assets/ninjas.json');
}
如果我的控制台显示以下内容,我该如何解决 app.component 的 subcribe() 问题:错误类型错误:无法读取 属性 'subscribe'未定义的 在 AppComponent.push../src/app/app.component.ts.AppComponent.ngOnInit
data.service:
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()))}}
app.components:
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;
);
}
}
Return 您服务中的可观察对象,
fetchData(){
return this.http.get('assets/ninjas.json').pipe(
map((res) => return res.json()))}}
只需删除 'pipe',您不需要它:
fetchData(){
return this.http.get('assets/ninjas.json');
}