【问题标题】:Getting GET http://localhost:4200/null 404 (Not Found) in angular以角度获取 GET http://localhost:4200/null 404(未找到)
【发布时间】: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 =&gt; this.smallPatchUrl = x.links.patch.small)(可能添加像if(x &amp;&amp; x.links &amp;&amp; x.links.patch) 这样的空检查并使用*ngIf="this.smallPatchUrl" 和其他'url'属性的类似用途。
  • 好的,我会尽量准确一点:*ngIf="this.smallPatchUrl" [style.backgroundImage]="url(this.smallPatchUrl)"
  • 谢谢@Pac0 这有效,但我将其更改为[style.backgroundImage]="'url('+this.smallPatchUrl+')'"。太感谢了!不再有跳过跟踪错误

标签: angular typescript


【解决方案1】:

async 管道不太适合以这种方式使用。

我建议在你的组件代码中使用一个中间变量来保存你的异步操作的结果

public smallPatchUrl: string;

(我假设这个 url 的类型是 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 + ')'"

这样,当nullundefined 时,您的组件将永远不会使用this.smallPatchUrl

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-10
    • 2018-08-01
    • 2021-06-28
    • 1970-01-01
    • 2017-05-13
    • 2018-05-25
    • 2018-03-16
    相关资源
    最近更新 更多