在本地主机上找不到图像,角度404错误

时间:2020-09-16 20:54:30

标签: javascript angular typescript

我有一个8号角的应用程序。

我有这样的服务


@Injectable({
  providedIn: 'root'
})
export class GetProfileImageUrl {
  profileImagefile: File;

  constructor(private sanitizer: DomSanitizer) {}

  profileImageUrlDefault() {
    return this.profileImagefile === null
      ? '/assets/placeholder.jpg'
      : this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(this.profileImagefile));
  }
}

我有一个调用此函数的组件,如下所示:

  get profileImageUrl() {
    return this.getImageUrl.profileImageUrlDefault;
  }

在构造函数中,我有这个:

private getImageUrl: GetProfileImageUrl

,模板如下所示:

<img [src]="profileImageUrl" width="147px" />

但是我得到这个错误:

profileImageUrlDefault()%20%7B%20%20%20%20%20%20%20%20return%20this.profileImagefile%20===%20null%20%20%20%20%20%20%20%20%20%20%20%20:1 GET http://localhost:4200/profileImageUrlDefault()%20%7B%20%20%20%20%20%20%20%20return%20this.profileImagefile%20===%20null%20%20%20%20%20%20%20%20%20%20%20%20?%20%27/assets/placeholder.jpg%27%20%20%20%20%20%20%20%20%20%20%20%20:%20this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(this.profileImagefile));%20%20%20%20} 404 (Not Found)
Image (async)

所以我的问题是。我必须改变什么?

谢谢

对不起,是我打来的:

如果我这样做:

 get profileImageUrl() {
    return this.getImageUrl.profileImageUrlDefault();
  }

我收到此错误:

core.js:5871 ERROR TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.
    at GetProfileImageUrl.profileImageUrlDefault (get-profile-image-url.ts:15)
    at ProfileInformationComponent.get profileImageUrl [as profileImageUrl] (profile-information.component.ts:86)
    at ProfileInformationComponent_Template (profile-information.component.html:3)
    at executeTemplate (core.js:11926)
    at refreshView (core.js:11773)
    at refreshComponent (core.js:13213)
    at refreshChildComponents (core.js:11504)
    at refreshView (core.js:11825)
    at refreshComponent (core.js:13213)
    at refreshChildComponents (core.js:11504)

1 个答案:

答案 0 :(得分:1)

在服务文件中,需要进行一次更改。三元方程式( === )应替换为双倍数( == )。

@Injectable({
providedIn: 'root'
})
export class GetProfileImageUrl {
  profileImagefile: File;

  constructor(private sanitizer: DomSanitizer) {}

  profileImageUrlDefault() {
    return this.profileImagefile == null
      ? '/assets/placeholder.jpg'
      : this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(this.profileImagefile));
  }
}

应该在打字稿文件中进行另一项更改。服务文件中包含的 profileImageUrlDefault 功能应按以下方式调用。

get profileImageUrl() {
  return this.getImageUrl.profileImageUrlDefault();
}

link可让您访问实时的stackblitz环境,在进行上述调整后,解决方案可以正常工作。

希望这个答案可能会有所帮助。