首页 > 解决方案 > 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 调用的帖子)并且无法弄清楚我的问题。

标签: angulartypescripthttp

解决方案


实际上,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,
    );
  }


推荐阅读