I am currently working on a project that involves retrieving data from a custom server. I have created an httpclient service to handle requests, but I am facing an issue. When I attempt to subscribe and pass data to the component, nothing happens. However, if I perform the subscription directly in the component, everything works as expected. Below is a summarized version of the code:
The component:
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { BehaviorSubject, catchError, map, Observable, of} from 'rxjs';
import { Food } from '../api/api-models';
import { ApiService } from '../api/api.service';
@Component({
selector: 'app-in-home-list',
templateUrl: './in-home-list.component.html',
styleUrls: ['./in-home-list.component.css']
})
export class InHomeListComponent implements OnInit {
res: Food[];
error: string;
constructor( private api: ApiService, private http: HttpClient){
}
ngOnInit() {
//this.http.get<Food[]>('https://localhost:5001/').pipe(catchError(this.api.handleError)).subscribe({next: r => this.res = r, error: e => this.error = e});
[this.res, this.error] = this.api.getInHomeList();
}
}
The commented line works inside the component, but not in the service. The uncommented part is what I want to function correctly.
The service:
import { Injectable} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Food } from './api-models';
import { catchError, throwError } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ApiService {
private result: Food[];
private error: string;
constructor( private http: HttpClient) {
}
getInHomeList(): [Food[], string] {
this.http.get<Food[]>('https://localhost:5001/').pipe(catchError(this.handleError)).subscribe({next: r => this.result = r, error: e => this.error = e});
return [this.result, this.error];
}
handleError(error: any) {
let errorMessage = "";
if (error.error instanceof ErrorEvent) {
// client-side error
errorMessage = `Error: ${error.error.message}`;
} else {
// server-side error
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
console.log(errorMessage);
return throwError(() => new Error(errorMessage))
}
}
The @NgModule in app.module.ts:
@NgModule({
declarations: [
AppComponent,
InHomeListComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
],
providers: [
ApiService
],
bootstrap: [AppComponent]
})
As a newcomer to Angular, I may be missing something or not fully understanding how Observables work.