Angular Сервис - Наблюдаемые отсутствуют свойства - PullRequest
0 голосов
/ 02 апреля 2020

Я новичок в angular и пытаюсь заставить работать этот HTTP-вызов. Я видел много примеров запросов get для массивов и пытался адаптировать его только к одному объекту (профилю пользователя), но безуспешно. Я получаю эту ошибку: enter image description here

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 (включая ту, которая по совпадению также касается вызова API getProfile) и не смог понять мою проблему.

1 Ответ

3 голосов
/ 02 апреля 2020

На самом деле, вы не получаете Profile, когда звоните 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,
    );
  }

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...