#http request

11 messages · Page 1 of 1 (latest)

rich sphinx
#

Can somebody please help me how to make an accurate http request using angular? not even chat gpt can do this right, i sent the code and it doesnt know how to fix it

HTML
<h1>Products</h1>

<div *ngFor="let product of products">
<div class="card">
<h3>{{ product.title }}</h3>
<p>{{ product.description }}</p>
<strong>R$ {{ product.price }}</strong>
</div>
<p>Total: {{ products.length }}</p>
</div>

TS

import { Component, OnInit, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Product } from '../product';
import { ProductService } from './apiservice';

@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule],
templateUrl: './app.html',
styleUrls: ['./app.css'],
})
export class App implements OnInit {
constructor(private productService: ProductService) {
console.log('App constructor executed');
}

protected readonly title = signal('angular-cart');
products: Product[] = [];

ngOnInit(): void {
console.log('ngOnInit executed');
this.loadProducts();
}

loadProducts(): void {
console.log('Calling loadProducts');

this.productService.getProducts().subscribe({
  next: (response) => {
    console.log('API response:', response);
    this.products = response.products;
    console.log('Products set:', this.products);
  },
  error: (error) => console.log('Request error:', error),
});

}
}

BTW the console shows no errors. It shows the http sequest as sucessful in the console, but nothing happens in the screen.

#

this is te service import { HttpClient } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Product } from '../product';

@Injectable({
providedIn: 'root',
})
export class ProductService {
private http = inject(HttpClient);
private apiUrl = 'https://dummyjson.com/products';

getProducts(): Observable<{ products: Product[] }> {
return this.http.get<{ products: Product[] }>(this.apiUrl);
}
}

tough summit
#

This is possibly due to using Zoneless (the default behavior since Angular 21, implicit, and recommended).

One solution is to use signal for the Products array so that the correct value is refreshed on the screen.

Alternatively, you can use httpResource (this is experimental and not yet recommended for production).

I would recommend using toSignal to convert the observable or signal.

On the other hand, if you want to use AI to study Angular, I recommend AI Tutor and the custom instructions/skills for using it, which are updated and maintained by the Angular Team.

ChatGTP or AI without context will most likely give you outdated information.

Note: Avoid using CommonModule and NgIf/NgFor (they are deprecated and soon to be removed).

rich sphinx
#

Thank you for your answer, @tough summit. So i used the AI tutor that you reccommend me and it helped me a lot. But it's a little frustating that this ''old'' method is not working well or is unstable

tough summit
#

The old method actually "works" if you use ChangeDetectorRef and use detectChanges or markforCheck

I recommend reviewing how ChangeDetection works in Angular; it will give you a general idea of ​​how it worked before and how things work now without Zone.js (also, in Angular 22 we'll have OnPush by default). So it's advisable to read it anyway.

south quartz
#

@rich sphinx few general suggestions:

  • Signals and Observables should always be in readonly properties. Since they are "pipelines" in a sense that update the value they contain automatically, so these pipelines themselves should never change/get reassigned. The keywords here are "declarative programming", which Angular is centered around. If you want your LLM of choice to give you decent suggestions or explanations, I'd recommend adding that to the prompt
  • You should never under any circumstances subscribe to an observable, just to get the current value out of it. That's an anti-pattern and as SkyZeroZx pointed out, will not work with more efficient changeDetection
  • The goal is for all values that change over time to be either signals, or observables
  • If you have an observable and want its value, transform it into a signal via toSignal or use the async pipe (e.g. myObs$ | async) inside your template
  • For your specific scenario I'd also more recommend httpResource, there are ways to do this with rxjs but that might be a bit much when you're still starting out, it requires actually understanding rxjs, e.g. how switchMap/concatMap/exhaustMap work and what Subjects are, potentially even the startWith operator
rich sphinx
#

@south quartz @tough summit Thank you very much for the explanations. I had no idea it was that deep. I’m going to follow all your advice and try to read more of the documentation, because for some reason AI is very outdated when it comes to this subject and gives incorrect code.

gritty python
#

httpResource is best choice