我正在尝试使用Angular(SPA模板)在ASP.NET CORE中从头开始创建项目。我已经创建了基本的API和表单,但是在网络->响应中接收数据时无法获取数据。这是我的代码
API控制器
[HttpGet]
public IActionResult Get()
{
var res = Json(UsersBAL.GetAll());
return res;
}
角度组件
import { Component, OnInit } from '@angular/core';
import { UsersService } from '../../Services/users.service';
@Component({
selector: 'app-vehicle-form',
templateUrl: './vehicle-form.component.html',
styleUrls: ['./vehicle-form.component.css']
})
export class VehicleFormComponent implements OnInit {
users: any;
constructor(private usersService: UsersService) { }
ngOnInit() {
this.usersService.getUsers().subscribe((data: any) => {
this.users = data;
console.log("Users : ",data);
},
error => {
console.log(error)
})
//console.log("Users : ",this.users);
}
}
角度服务
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class UsersService {
api_url = 'http://localhost:58508/api/';
constructor(private http: HttpClient) { }
getUsers() {
return this.http.get(this.api_url + 'Users')
.pipe(map((response: any) => response.json()))
.pipe(
tap(_ => console.log('fetched users')),
catchError(this.handleError('getusers', []))
);
}
private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// TODO: better job of transforming error for user consumption
console.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
}
答案 0 :(得分:0)
您不需要map(res => res.json())
中的HttpClient
。默认情况下,它采用JSON并立即为您解析。
因此只需在服务中将其返回:
getUsers() {
return this.http.get(this.api_url + 'Users')
.pipe(
tap(_ => console.log('fetched users')),
catchError(this.handleError('getusers', []))
);
答案 1 :(得分:0)
从.pipe(map((response: any) => response.json()))
方法中删除此行get
。
HttpClient
默认提供json
响应数据。
return this.http.get(this.api_url + 'Users')
// .pipe(map((response: any) => response.json())) -- not required
.pipe(
tap(_ => console.log('fetched users')),
catchError(this.handleError('getusers', []))
);