我的后端使用ASP.NET Core而前端使用Angular。 我有一个api,它从后端给我作为json的数据。
我创建了一个加载api-data的服务,但它只是返回' undefined'。
employee.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';
import { Employee } from './employee';
//interface Employee_interface {
// id: number;
// name: string;
//}
@Injectable()
export class EmployeeService {
constructor(public http: HttpClient, private _httpService: Http) {}
//apiEmployees: JSON;
employees: Employee[];
stuff: Object;
getEmployees(): Observable<Employee[]> {
this.http.get('/api/employees').subscribe(data => { console.log(data); }); //I can see an array with my json-data from the api
this.http.get('/api/employees').subscribe(data => this.stuff = data);
console.log("LOG: " + this.stuff); //LOG: undefined
console.log("LOG1 :" + this.http.get('/api/employees').pipe()); //LOG1 :[object Object]
return this.http.get('/api/employees').pipe();
}
}
我有什么要回来的?
app.components.ts
import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { HttpClient } from '@angular/common/http';
import { Employee } from './employee';
import { EmployeeService } from './employee.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
title = 'app';
employees: Employee[];
constructor(public http: HttpClient, private _httpService: Http, private employeeService: EmployeeService) { }
ngOnInit() {
this.getEmployees();
}
getEmployees(): void {
this.employeeService.getEmployees()
.subscribe(employees => this.employees = employees);
}
}
有人能帮帮我吗?先谢谢你!
答案 0 :(得分:0)
改变这个:
return this.http.get('/api/employees').pipe();
进入这个:
return this.http.get('/api/employees')
.map(response => response.json())
.catch((error: any) => Observable.throw(
{ message: error.json().message, details: error.json().details }));
这里我们处理错误(首先要弄清楚出了什么问题,如果出错了)我们正在将响应解析为JSON。
希望它有用。