angular - Angular Service - Observable 缺少属性
问题描述
我是 Angular 的新手,我正在尝试让这个 HTTP get 调用工作。我已经看到了许多获取数组请求的示例,并尝试将其调整为仅适用于单个对象(用户配置文件),但没有成功。我收到此错误:
profile.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { Profile } from '../models/profile.class';
@Injectable({
providedIn: 'root'
})
export class ProfileService {
apiURL = 'http://localhost:8080';
constructor(private httpClient: HttpClient) { }
getProfile(userId: string) {
const params = new HttpParams().set('id', userId); // create new HttpParams
return this.httpClient.get<Profile>(`${this.apiURL}/user`, {params})
.pipe(
map((data: any) => {
const profile: Profile = new Profile( data.object.id,
data.object.info.username,
data.object.info.password,
data.object.info.fname,
data.object.info.lname,
data.object.info.email,
data.object.joined );
return profile;
})
);
}
}
profile.component.ts:
import { Component, OnInit } from '@angular/core';
import { ProfileService } from '../services/profile.service';
import { Profile } from '../models/profile.class';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
profile: Profile;
constructor(private profileService: ProfileService) {
}
ngOnInit() {
}
getProfile() {
this.profile = this.profileService.getProfile( "5e7bd87e05854a05cc0f6898" );
}
}
***注意:我已经阅读了关于 SO 的所有相关帖子(包括巧合也处理 getProfile API 调用的帖子)并且无法弄清楚我的问题。
解决方案
实际上,Profile
当您调用时,您不会得到 a,this.profileService.getProfile( "5e7bd87e05854a05cc0f6898")
而是会得到 Observable。
所以,你有两种方法可以解决这个问题:
// #1
async getProfile() {
this.profile = await this.profileService.getProfile("5e7bd87e05854a05cc0f6898").toPromise();
}
// #2
getProfile() {
this.profileService.getProfile("5e7bd87e05854a05cc0f6898").subscribe(
profile => this.profile = profile,
);
}
推荐阅读
- google-cloud-platform - 如何使用 stackdriver 从对话流中检索对话数据?
- laravel - 示例 laravel 项目 error500
- ruby-on-rails - Letter_opener 不再起作用的原因是什么?
- spring - 将石英与弹簧调度程序一起使用时未创建 Bean 引用 - 作业实例化失败
- python - wxPython - 如何“突出显示”一个 TextCtrl?
- string - 如何从文本文件中读取文本而不检索“ß”或“ä”等字符?
- c# - http 不使用 IIS 10 中的整个 URL 的 Url Rewrite 重定向到 https(包含参数的 URL)
- c# - 如何使用 RestSharp 发送带有动态属性的 JSON?
- python - 在字符串中转义 \u
- java - Android UDP Socket IOException: sendto failed: EPERM (Operation not allowed)