当我尝试从asp.core api返回响应时,我遇到了问题 " angular 2 http get Object {_body:error,status:0,ok:false,statusText:"",headers:{...},type:3,url:null}&#34 ;
组件:
import { Component, OnInit } from '@angular/core';
import { IIndustryType } from '../../../model/IndustryType';
import { DeveloperJobDataService }from'../../../services/developerjob.dataservice';
@Component({
selector: 'add-job',
templateUrl: './addJob.component.html',
styleUrls: ['./addJob.component.css'],
providers: [DeveloperJobDataService]
})
export class AddJobComponent {
errorMessage: string;
private industry: IIndustryType[];
constructor(private dataService: DeveloperJobDataService) {
this.dataService.GetIndustries().subscribe(result => {
this.industry = result.json() as IIndustryType[];
console.log(this.industry);
}, error => console.error(error));
}
}
接口:
export interface IIndustryType {
id: number,
name: string,
description: string,
isActive: boolean,
createdDate: Date
}
服务:
import { Injectable } from '@angular/core';
import { Http, Response, RequestOptions } from '@angular/http';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { IIndustryType } from '../model/IndustryType';
import { IndustryType } from '../model/viewModel';
@Injectable()
export class DeveloperJobDataService {
private baseUrl: string = 'http://localhost:49861/api/Industries';
constructor(private http: Http) { }
public GetIndustries() {
return this.http.get(this.baseUrl);
}
}
错误:
答案 0 :(得分:1)
您错过requestOptions
中的HTTP方法,如下所示:
https://angular.io/api/http/Http#request
您的示例没有帖子正文;我猜你想用Http Get。如果不是,您可以根据自己的情况更改HttpMethod
public GetIndustries() {
return this.http.request(this.baseUrl,{
method : 'Get' // or 'Post'
});
}
或者您可以使用get
代替request
public GetIndustries() {
return this.http.get(this.baseUrl);
}
答案 1 :(得分:0)
试试这个。
像这样更改GetIndustries
方法。
public GetIndustries() Observable<IIndustryType[]>{
return this.http.get<IIndustryType[]>(this.baseUrl);
}
在您调用GetIndustries
方法的组件构造函数中执行这些更改。
constructor(private dataService: DeveloperJobDataService) {
this.dataService.GetIndustries().subscribe(result => {
this.industry = result;
console.log(this.industry);
}, error => console.error(error));
}