我想在我的角度应用和我的REST API之间建立连接。
这里它返回JSON http://is.njn.mvm.bg/check。所以我的问题是我需要哪些提供者,因为我包含在app.module中,但它仍然不起作用。
print
我正在使用Angular2 HTTP教程
import { HttpModule} from '@angular/http';
我正在 private heroesUrl = 'http://is.njn.mvm.bg/check'; // URL to web API
constructor (private http: Http) {}
getHeroes (): Observable<Hero[]> {
return this.http.get(this.heroesUrl)
.map(this.extractData)
.catch(this.handleError);
}
答案 0 :(得分:2)
您正在使用http请求错误。请使用以下代码。
<强> app.component.ts 强>
//our root app component
import { Component } from '@angular/core'
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Component({
selector: 'root',
template: `
<div>
{{people}}
{{ err}}
</div>
`
})
export class App {
people;
err;
constructor(http:Http) {
http.get('http://is.njn.mvm.bg/check').map(res => res.text()).subscribe(people => this.people = people,err=>this.err = err);
// Subscribe to the observable to get the parsed people object and attach it to the
// component
}
}
&#13;
还记得 在您的控制台中发生以下错误: 接入控制允许来源
For remove this error see:
答案 1 :(得分:1)
您需要输入标头参数&#34; Access-Control-Allow-Origin&#34;在服务器的HTTP响应中。您无法仅从客户端进行此项工作。尝试从Java JSON REST服务器获取数据时,我也遇到了同样的问题。我不确定你使用服务器端,但在Java中看起来像这样:
public class PriceList <String, Double> implements Map <String, Double> {
private static PriceList instance = null;
protected PriceList() {}
public static PriceList getInstance() {
if (instance == null)
instance = new PriceList();
return instance;
}
public void put(String string, double d) {
// TODO Auto-generated method stub
}}
有关此错误(CORS)的信息,请参阅:
答案 2 :(得分:0)
您还需要将其添加到imports
@NgModule
@NgModule({
imports: [BrowserModule, HttpModule]
...
})
答案 3 :(得分:0)
您的模块代码如下所示:
@NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
],
declarations: [
AppComponent
],
providers: [
{provide: APP_BASE_HREF, useValue: '/'},
],
bootstrap: [AppComponent]
})
export class AppModule {
}
您的服务代码需要与此类似
constructor(private http: Http) {
}
getCountriesByRegion(region: string) {
return this.http.get(this.countries_endpoint_url + region).map(res => res.json());
}
//you can also do like this
getHeroes(): Observable<any[]> {
return this.http.get(this.heroesUrl)
.map(this.extractData)
.catch(this.handleError);
}
答案 4 :(得分:0)
您拥有在端口3000上运行的服务器所服务的Angular应用程序,但此应用程序尝试对在另一个端口8000上运行的服务器进行HTTP调用。
您有两种选择: 1.在端口8000上运行的服务器下部署Angular应用程序,在这种情况下,您的Angular应用程序将在其提供的同一端口上运行。 2.在端口3000上运行的服务器上配置代理,以允许访问端口8000。
对于第二种情况,如果对项目使用Angular CLI,请创建一个文件proxy-conf.json,例如:
{
"/api": {
"target": "http://localhost:8000",
"secure": false
}
}
然后像这样设置你的Anglar应用程序:
ng serve --proxy-config proxy-conf.json