Angular rxResource - Data not being displayed on template but data is fetched

Discussão em 'Angular' iniciado por kibet, Abril 25, 2025.

  1. kibet

    kibet Guest

    I am trying to display data using rxResource. However, data returned is always undefined. However, inspecting the network tabs shows the data is indeed being fetched and I'm just doing something wrong on my component. What is the issue with this code? Because I can't seem to find what the problem is

    API service

    import { HttpClient } from '@angular/common/http';
    import { inject, Injectable } from '@angular/core';
    import { httpResource } from "@angular/common/http";

    @Injectable({
    providedIn: 'root'
    })
    export class ApiService {
    private readonly httpClient = inject(HttpClient);

    public GET<T>(path: string, options?: any) {
    return this.httpClient.get<T>(path, options);
    }


    Component file:

    import { Component, inject, signal } from '@angular/core';
    import { ApiService } from '@services/api.service';
    import { rxResource, toSignal } from '@angular/core/rxjs-interop';
    import { distinctUntilChanged, map } from 'rxjs';

    @Component({
    selector: 'app-blogs',
    templateUrl: './blogs.component.html',
    styleUrl: './blogs.component.scss'
    })
    export class BlogsComponent {

    apiService = inject(ApiService)
    query = signal('')

    rxBlog = rxResource({
    request: () => this.query(),
    loader: () =>
    this.apiService.GET(`https://api.nationalize.io/?name=${this.query()}`)
    .pipe(
    distinctUntilChanged(),
    map((blogs) => blogs),
    )
    })

    search(event: Event) {
    const { value } = event.target as HTMLInputElement;
    this.query.set(value);
    }
    }


    // Template
    <p>blogs works!</p>

    <input (input)="search($event)" placeholder="Search user..."/>

    <br />
    <ul>
    @let error = rxBlog.error();

    @if (error) {
    <p>{{ error }}</p>
    }

    @if (rxBlog.isLoading()) {
    <p>Loading Blogs...</p>
    }

    @for (blog of (rxBlog.value()).country) {
    {{blog.country_id}}
    }

    </ul>


    Json data looks like below:

    {
    "count": 22997,
    "name": "steve",
    "country": [
    {
    "country_id": "KE",
    "probability": 0.0728971981962264
    },
    ]
    }

    Continue reading...

Compartilhe esta Página