From my understanding of async pipe, it's a quicker way of subscribing to an observable in fewer lines. However I'm trying to understand in what circumstances would I need to use it over a traditional subscription like my current component below?
import { Component, OnInit } from '@angular/core';
import { HttpService } from "./services/http.service";
import { Main } from "./interfaces/data-interface";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor(private httpService: HttpService) {
}
mainData: Main;
itemIndexFocus: number = 0;
ngOnInit() {
this.httpService.getFighterDetail()
.subscribe((res) => {
this.mainData = res.body;
});
}
}
httpservice file:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Observable } from 'rxjs';
@Injectable()
export class HttpService {
constructor(private http: HttpClient) { }
getFighterDetail(): Observable<any> {
return this.http.get("/MYAPI", { responseType: 'json', observe: 'response' })
}
}
It is just a case that I could always use async pipe? If I'm populating a reactiveform with values from an api then I guess my above component's approach would be the more beneficial one.
CodePudding user response:
You can start by reading this.
Http is an observable that is automatically complete once the reponse is receive so it a nonsense to use a async pipe on it.
Async pipe is really powerfull with NgRx. Here you can find few lines about subscribe vs async pipe
CodePudding user response:
Pipes are used to modify the data / add extra logic & other fun stuff to an observable. Pipes do not "subscribe" to an observable
Yeah you could definitely not use pipes, but then you are missing out on the functionality & cleaner code they provide
For example, if you have some user service that gets a list of users from your API, you'll have to also account for when the server is unavailable, or returns an error code.
Let's say multiple components use this user service, do you want to add error handing to all your components? That's pretty messy. Alternatively in the service you can pipe your error handling
This way each component that needs users doesn't have to care about error handling