繁体   English   中英

Angular:如何使用http.get返回的class实例

[英]Angular : How to use the instance of class returned by http.get

客户端组件

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-client',
  templateUrl: './client.component.html',
  styleUrls: ['./client.component.css']
})
export class ClientComponent implements OnInit {
  client:Client=new Client();
constructor(private clientService:ClientService) { }

ngOnInit() {
     this.ClientService.getClient("4").subscribe(data=>this.client=data);
     console.log(this.client) //it shows (new Client() "empty")
}

}

服务

import { HttpClient } from '@angular/common/http'; 
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Client} from 'src/app/client';

@Injectable({
  providedIn: 'root'
 })
export class ClientService {

private baseUrl ="http://localhost:8080/api/v1/client"
constructor( private httpClient: HttpClient ) { }


getClient(id:string) :Observable<Client>{
  return this.httpClient.get<Client>(`${this.baseUrl}/${cin}`);
 }

}

我不能在我的数据库中使用客户端。 httpClient.get return Observable 我希望它返回 Client 这样我就可以在我的应用程序中使用它

尝试在订阅中添加console.log

ngOnInit() {
 this.ClientService.getClient("4").subscribe(data => {
    this.client = data;
    console.log(this.client);
 });
}

当您订阅一个observable时,其中的逻辑就变成了asynchronous的。 ngOnInit中的console.log不会等待this.client存储值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM