我试图调用API服务,并在控制台中以类的形式在构造函数的帮助下以对象形式打印其响应
我正在运行调用API服务的Typescript
import * as request from "request";
import { Users } from "./Users";
export class GitubHubApiService{
getUserInfo(username : String){
let options : any = {
headers:{
"User-Agent" :"request"
},
json : true
}
request.get("https://api.github.com/users/"+ username ,options,(error:any , Response : any,body: any) => {
console.log((body));
let user = new Users((body));
console.log(user);
})
}
}
This class form the object using those response from API Service call.
export class Users{
login : String;
fullName : String;
repoCount : number;
followerCount : number;
constructor(userRes :any){
this.login = userRes.login;
this.fullName = userRes.name;
this.repoCount = userRes.public_repos;
this.followerCount = userRes.followers;
}
}
用户{ 登录名:未定义, fullName:未定义, repoCount:未定义, followerCount:未定义}
答案 0 :(得分:0)
您不能这样分配,请使用getter和setter
import * as request from "request";
import { Users } from "./Users";
export class GitubHubApiService{
getUserInfo(username : String){
let options : any = {
headers:{
"User-Agent" :"request"
},
json : true
}
request.get("https://api.github.com/users/"+ username ,options,(error:any , Response : any,body: any) => {
console.log((body));
let user = new Users();
user.data = body;
console.log(user.data);
})
}
}
此类使用get和set方法通过API服务调用的响应来形成对象
export class Users{
login : String;
fullName : String;
repoCount : number;
followerCount : number;
constructor(){
}
set data(userRes :any) {
this.login = userRes.login;
this.fullName = userRes.name;
this.repoCount = userRes.public_repos;
this.followerCount = userRes.followers;
}
get data() {
return { login: this.login, fullName: this.fullName, repoCount:this.repoCount, followerCount: this.followerCount}
}
}
我怀疑您是否会像这样简单地使用
export class GitubHubApiService{
getUserInfo(username : String){
let options : any = {
headers:{
"User-Agent" :"request"
},
json : true
}
request.get("https://api.github.com/users/"+ username ,options,(error:any , Response : any,body: any) => {
console.log((body));
let user = { login: body.login, fullName: body.name, repoCount: body.public_repos, followerCount:followers }
console.log(user);
})
}
}