I am working on an angular app using ng9.
I have a div in which I want to set an avatar using using an image from the api. In the component.ts
....
export class HomeComponent implements OnInit {
nextLaunch$: Observable<SpacexNext>;
panelOpenState: true;
search = '';
constructor(
private spacexService: SpacexService,
private sanitizer: DomSanitizer
) { }
ngOnInit(): void {
this.nextLaunch$ = this.spacexService.getNextLaunch();
}
...
in the .html
<div mat-card-avatar *ngIf="(nextLaunch$ | async)?.links?.patch?.small !== null" [style.backgroundImage]="'url('+(nextLaunch$ | async)?.links?.patch?.small+')'" class="example-header-image">
</div>
This works perfectly and the avatar is set as expected, however I have I get an error in the browser console:
GET http://localhost:4200/null 404 (Not Found)
Any ideas to get rid of the error?
More Info..
The api works well and my service returns data as expected. The avater image is displayed without any problem. My only issue is the error that appears on the browser console. I had done some research and saw that using async pipe could be the cause of the issue but I prefer this rather than subscribe method.
TIA.
='url('+(nextLaunch$ | async)?.links?.patch?.small+')'"assign it a variable in your controller. Then, don't use theDomSanitizerand[style.backgroundImage]but instead set a CSS class, which is more idiomatic. That said, you need to show us anhttp.get()(probably inspacexService.getNextLaunch()) which is triggering your error. Maybe?public smallPatchUrl: string(or other correct type), usethis.spacexService.getNextLaunch().subscribe(x => this.smallPatchUrl = x.links.patch.small)(maybe add null checks likeif(x && x.links && x.links.patch)and use*ngIf="this.smallPatchUrl"and similar use for other 'url' attribute.*ngIf="this.smallPatchUrl" [style.backgroundImage]="url(this.smallPatchUrl)"[style.backgroundImage]="'url('+this.smallPatchUrl+')'". Thank you so much! No more skip trace errors