我是Angular 4的新手,我正在尝试用api制作简单的应用程序。但是Get请求不起作用,我不知道问题出在哪里。
我的服务:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class RequestService {
// persos:any;
constructor(private http:Http) {
this.getPersos();
}
getPersos() {
return this.http.get(this.apiUrl + 'people/')
.map(response => {
return response.json(),
console.log(response.json());
})
}我的组件文件:
import { Component, OnInit } from '@angular/core';
import { Http, Response, RequestOptions } from '@angular/http';
import { RequestService } from '../services/requests.service'
@Component({
selector: 'persos',
templateUrl: './persos.component.html',
styleUrls: ['./persos.component.css'],
providers: [RequestService]
})
export class PersosComponent implements OnInit {
constructor(private requestService:RequestService) {
console.log(this.persos);
}
title = 'List des personnages';
persos;
ngOnInit() {
this.requestService.getPersos()
.subscribe(persos => {
this.persos = persos;
console.log(this.persos);
})
}
}在服务文件中,我放了一个返回给我的好数据的日志,但组件文件中的console.log返回'undefined‘。
我还没有找到解决方案。谢谢您的提前付款。
发布于 2017-07-10 04:01:56
将您的console.log添加到subscribe中,您的组件方法方法也应该是
this.requestService.getPersos().subscribe(persos => {
this.persos = persos;
console.log(this.persos);
});你的服务应该是,
return this.http.get(this.apiUrl + 'people/')
.map(response => {
return response.json(),
console.log(response.json());
})发布于 2017-07-10 04:05:09
您能否确认您尝试访问的API URL存在/工作正常?另外,我对这个代码有点怀疑。
return this.http.get(this.apiUrl + 'people/')
.map(response => {
response.json(),
console.log(response.json());
})你有response => {response.json(), console.log(response.json());}),我有种不起作用的感觉。
此外,当您订阅一个可观察对象时,您不会将值设置为subscribe()。您可以在subscribe()调用内部的函数中设置该值。
this.requestService.myMethod().subscribe(result => {
this.persos = result;
console.log(this.persos);
});https://stackoverflow.com/questions/45000465
复制相似问题