Angular 2 http获取不获取 [英] Angular 2 http get not getting
问题描述
我刚接触Angular 2仍在学习,我试图通过get调用来访问URL,但是即使在浏览器网络中,get也似乎没有通过,我找不到被调用的URL.
I new to Angular 2 still learning I am trying to hit a URL with a get call but the get doesn't seem to go through even in browser's network I cannot find that get URL being called.
程序将在该方法控制台上记录该get调用的上方和下方,但对于get调用则无任何作用
The program is going to that method console logging above and below that get call but nothing for the get call
我的服务方式
import { Headers, Http, Response } from '@angular/http';
import { Injectable } from '@angular/core';
import { Persons } from './mock-people';
import { Person } from './person';
import {Observable} from 'rxjs/Rx';
getAllPersons(): void {
console.log("Here");
this.http.get(`http://swapi.co/api/people/1`)
.map((response: Response) => {
console.log(response.json());
response.json();
});
console.log("Comes here 2");
}
在app.module.ts中导入HttpModule
Imported HttpModule
in app.module.ts
我的控制台屏幕截图
推荐答案
Http使用rxjs且可以观察到冷/懒惰,这意味着您应该订阅它才能使其正常工作.
Http uses rxjs and is a cold/lazy observable, meaning that you should subscribe to it to make it work.
this.http.get(`http://swapi.co/api/people/1`)
.map((response: Response) => {
console.log(response.json());
response.json();
})
.subscribe();
或者如果您想从其他地方订阅,则应返回http.get
方法,如下所示:
Or if you want to subscribe from somewhere else, you should return the http.get
method like this:
getAllPersons(): Observable <any> {
console.log("Here");
return this.http.get(`http://swapi.co/api/people/1`)
.map((response: Response) => {
console.log(response.json());
return response.json();
});
}
然后:
getAllPersons().subscribe();
这篇关于Angular 2 http获取不获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!