问题描述
我是 Angular 2 的新手,仍在学习我正在尝试通过 get 调用访问 URL,但即使在浏览器的网络中,get 似乎也没有通过,我找不到正在调用的 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 并且是一个冷/懒惰的 observable,这意味着您应该订阅它以使其工作.
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 没有得到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!