angular: Using userResource and @if some conditions dom does not render
Which @angular/* package(s) are the source of the bug?
common
Is this a regression?
No
Description
import {Component, signal} from '@angular/core';
import {httpResource} from '@angular/common/http';
import {FormsModule} from '@angular/forms';
@Component({
selector: 'index-item',
imports: [
FormsModule
],
template: `
<input type="number" [(ngModel)]="userId">
@if (userResource.isLoading()) {
<span>loading...</span>
} @else {
<span>Complete!</span>
@if (userResource.value().code) {
<span>data Length:{{ userResource.value().data.length }}</span>
}
}
`
})
export class Item {
userId = signal(1);
userResource = httpResource<any>(() =>
`https://example.com/v1/users/${this.userId()}`,
{
defaultValue: {
code: 200,
data: [1, 2, 3, 4, 5, 6, 7, 8, 9]
},
}
)
}
No Rendering
@if (userResource.value().code) {
<span>data Length:{{ userResource.value().data.length }}</span>
}
Please provide a link to a minimal reproduction of the bug
No response
Please provide the exception or error you saw
Please provide the environment you discovered this bug in (run ng version)
Angular CLI: 20.0.0
Node: 22.16.0
Package Manager: npm 10.9.2
OS: win32 x64
Angular:
...
Package Version
------------------------------------------------------
@angular-devkit/architect 0.2000.0 (cli-only)
@angular-devkit/core 20.0.0 (cli-only)
@angular-devkit/schematics 20.0.0 (cli-only)
@schematics/angular 20.0.0 (cli-only)
Anything else?
No response
About this issue
- Original URL
- State: closed
- Created a year ago
- Comments: 19 (2 by maintainers)
@JeanMeche The documentation says otherwise though:
(emphasis mine)
FYI: doc is now updated for this: https://github.com/angular/angular/pull/61846
Also see 2nd point in this issue for more info: https://github.com/angular/angular/issues/61789, it says its difficult to catch this error. but as I said it won’t throw an error if you check it using hasValue before accessing it.
Hi @HCenggel it seems with v20 you should not access value signal without calling
hasValue(), otherwise you will get such unexpected behaviour, also you won’t be able to display default value in this way if http api returns an error, instead you can store default value in another component field, and display that if API is in error state. Access value signal like this to prevent errors:In v20, the resource
valuethrows when theresourceis anerrorstate.This is as designed.
Ok, thanks, I could regenerate it, I tried to debug it seems Angular is throwing error instead of returning default value, related code: https://github.com/angular/angular/blob/42f07ce2f6cdd2152b39c14eb0248b75d4fe95c9/packages/core/src/resource/resource.ts#L195-L201