1

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]));
  }
Giannis
  • 1,790
  • 1
  • 11
  • 29
Prieto
  • 27
  • 1
  • 7

1 Answers1

1

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>
Joosep Parts
  • 5,372
  • 2
  • 8
  • 33
  • error in foro$: Forum = this.forumService.getById(this.id_foro); The type "Observable" is missing the following properties of the type "Forum": id, name, description, photo and 2 more. – Prieto May 09 '22 at 04:23
  • Sorry, it should have been `foro$: Observable` – Joosep Parts May 09 '22 at 05:21
  • it worked! but in component.html it doesn't recognize my forum attributes:_ Property 'nombre' does not exist on type 'Observable' – Prieto May 10 '22 at 17:42
  • Well the observable returns an object of type `Forum` if you want to access the property `nombre` on `Forum` we could use `| keyvalue` pipe or access the object directly in template by defining it `as` or using conditional property whatever suits you. More on this: https://stackoverflow.com/a/37147691/15439733 and I also edited my post for this. – Joosep Parts May 11 '22 at 05:40