I keep getting an empty Array, when using Angulars toSignal function.
The observable returns an array of 5 objects.
But the signal returns an empty array.
Below is the Service code, and Component code.
API Service
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SpringAPIService {
private readonly baseUrl = 'http://localhost:8080';
http = inject(HttpClient)
getData(endpoint: string): Observable<any> {
const url = `${this.baseUrl}/${endpoint}`;
const headers = new HttpHeaders().set('Content-Type', 'application/json');
const observable = this.http.get(url, { headers });
return observable;
}
}
Angular 17 Component
import { Component, Injector, Signal, inject, runInInjectionContext, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SpringAPIService } from '../spring-api.service';
import { toSignal } from '@angular/core/rxjs-interop';
@Component({
selector: 'app-projects',
standalone: true,
imports: [CommonModule],
templateUrl: './projects.component.html',
styleUrl: './projects.component.scss'
})
export class ProjectsComponent {
http: SpringAPIService = inject(SpringAPIService);
injector = inject(Injector);
data: Signal<any> = signal([])
ngOnInit() {
runInInjectionContext(this.injector, () => {
this.data = toSignal(this.http.getData('projects'), { initialValue: [] });
console.log(this.data())
});
}
}
initialValue. Try printing the value of the signal in the template and see if you get the results expected.