【发布时间】:2020-12-01 14:12:06
【问题描述】:
我正在使用 ng9 开发 Angular 应用程序。
我有一个 div,我想在其中使用来自 api 的图像来设置头像。 在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();
}
...
在.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>
这完美无缺,头像已按预期设置,但是我在浏览器控制台中收到错误:
GET http://localhost:4200/null 404 (Not Found)
有什么办法可以摆脱这个错误?
更多信息..
api 运行良好,我的服务按预期返回数据。 头像图像显示没有任何问题。 我唯一的问题是浏览器控制台上出现的错误。 我做了一些研究,发现使用异步管道可能是问题的原因,但我更喜欢这种方法而不是订阅方法。
TIA。
【问题讨论】:
-
@Pac0 是的,我很确定。当我注释掉这个 div 时,错误不再存在。此外,当我用 img 标签替换 div 时,它不会显示此错误,但这不是首选方法。
-
这就是为什么你没有在模板中加入这么多逻辑的原因——它使调试非常困难。而不是所有这些
='url('+(nextLaunch$ | async)?.links?.patch?.small+')'"在您的控制器中为其分配一个变量。然后,不要使用DomSanitizer和[style.backgroundImage],而是使用set a CSS class,这样更习惯用法。也就是说,您需要向我们展示触发您的错误的http.get()(可能在spacexService.getNextLaunch())。也许? -
好的,感谢反馈,顺便说一下我同意你的研究结果,异步管道可能不应该那样使用。我会创建一个
public smallPatchUrl: string(或其他正确的类型),使用this.spacexService.getNextLaunch().subscribe(x => this.smallPatchUrl = x.links.patch.small)(可能添加像if(x && x.links && x.links.patch)这样的空检查并使用*ngIf="this.smallPatchUrl"和其他'url'属性的类似用途。 -
好的,我会尽量准确一点:
*ngIf="this.smallPatchUrl" [style.backgroundImage]="url(this.smallPatchUrl)" -
谢谢@Pac0 这有效,但我将其更改为
[style.backgroundImage]="'url('+this.smallPatchUrl+')'"。太感谢了!不再有跳过跟踪错误
标签: angular typescript