Search code examples
angularangularjsapiserviceobservable

Initialize object with Subscribe


i'm getting data from APIs and I'm inicializing the data like this:

export class ForumComponent implements OnInit {

  @Input() id_foro: number = 3;

  nombre: string = '';
  desc: string = ''
  foro!: Forum;
  
  constructor(private forumService: ForumService) { }

    

  ngOnInit(): void {
    this.forumService.getById(this.id_foro).subscribe((data: Forum) => {
      this.foro = data;
    });
    
  }

}

How can I do that like this?

forum: Forum = this.forumService.getById(this.id_foro).subscribe();

GetById function:

getById(id: number): Observable<Forum> {
    return this.httpClient.get<Forum[]>(`http://localhost:3000/forum/${id}`)
    .pipe(map((response: Forum[]) => response[0]));
  }

Solution

  • getById is already returning an observable so there is no need to subscribe. Just react to the response using | async pipe.

    I'd suggest to remove the ! unless you are 100% sure, that there always will be a value (thought I doubt this).

    Let's add $ to indicate that it is an observable (it's just a way to name the variable, nothing else fancy).

    foro$: Observable<Forum> = this.forumService.getById(this.id_foro);
    
    <div>{{ foro$ | async }}</div>
    

    Edit to access the object from the observable

    <div *ngIf="(foro$ | async)?.nombre">{{ (foro$ | async)?.nombre }}</div>
    
    <ng-container *ngIf="foro$ | async as forum">
      <div *ngFor="let prop of forum | keyvalue">
          Key: <b>{{prop.key}}</b> and Value: <b>{{prop.value}}</b>
      </div>
    </ng-container>