[英]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.