如何解决以角度获取GET http:// localhost:4200 / null 404未找到
我正在使用ng9开发角度应用。
我有一个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();
}
...
.p中的
<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。
解决方法
async
管道不太适合以这种方式使用。
我建议在您的组件代码中使用一个中间变量,以保存异步操作的结果
public smallPatchUrl: string;
(我假设此网址的类型为string
,如有必要,请进行修改)。
在您的ngOnInit
中使用:
this.spacexService.getNextLaunch().subscribe(x => {
if (x && x.links && x.links.patch) {
this.smallPatchUrl = x.links.patch.small;
}
});
在模板代码中,您可以将其用于组件:
*ngIf="this.smallPatchUrl" [style.backgroundImage]="'url(' + this.smallPatchUrl + ')'"
这样,当您的组件是this.smallPatchUrl
或null
时,您的组件将永远不会使用。{p1
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。