简体   繁体   中英

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

Client Component

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")
}

}

Service

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}`);
 }

}

i cant use the client in my database. httpClient.get return Observable i want it to return Client so i can use it in my app

Try adding the console.log within the subscribe

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

When you subscribe to an observable , the logic in there becomes asynchronous . The console.log in your ngOnInit , doesn't wait for this.client to store the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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