根据Angular文档中的HttpClient。
HttpClient.get()方法将JSON服务器响应解析为匿名对象类型。它不知道该物体的形状是什么。
我的问题是我无法直接获得Json。我仍然需要在dash-board.component.ts
中使用Json.parse划线board.component.ts
import { PhoneBasicInfo } from './../Models/PhoneBasicInfo';
import { DashBoardServiceService } from './../Services/dash-board-serv
ice.service';
import { Component, OnInit } from '@angular/core';
import { PhoneRecord } from '../Models/PhoneRecords';
@Component({
selector: 'app-dash-board',
templateUrl: './dash-board.component.html',
styleUrls: ['./dash-board.component.css']
})
export class DashBoardComponent implements OnInit {
constructor(private service: DashBoardServiceService) { }
temp:any;
basicInfo: PhoneBasicInfo;
ngOnInit() {
this.service.getPhoneBasicInfo()
.subscribe(
basic => {
console.log(basic['companyName']) <- I should get the Json Object.
console.log(JSON.parse(basic)); <- I should not do this.
}
);
}
}
抱歉我的声誉不足以嵌入图片
我使用JSON.parse来获取数据。但是,这似乎不正确。
所以我的问题是通过HttpClient获取Json的正确方法是什么?
非常感谢你。
划线板service.service.ts
import { PhoneBasicInfo } from './../Models/PhoneBasicInfo';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { CATCH_ERROR_VAR } from
'@angular/compiler/src/output/abstract_emitter';
@Injectable({
providedIn: 'root'
})
export class DashBoardServiceService {
private url = 'http://localhost:57302/api/Phone';
constructor(private http:HttpClient) { }
getPhoneBasicInfo(): Observable<PhoneBasicInfo>{
return this.http.get<PhoneBasicInfo>(this.url);
}
}
PhoneBasicInfo.ts
export class PhoneBasicInfo{
companyName:string;
firstTrade: string;
}
答案 0 :(得分:0)
谢谢你们,伙计们。我的问题来自服务器API。 再次感谢你。