【问题标题】:How to properly implement "photo.service"?如何正确实施“photo.service”?
【发布时间】:2019-02-01 14:22:03
【问题描述】:

我使用的是 Angular 4。当我尝试输出图像时,出现 404 错误:

GET http://localhost:4200/photos/original/missing.png 404(未找到)

图像(异步)
DefaultDomRenderer2.setProperty@platform-b​​rowser.es5.js:2895 AnimationRenderer.setProperty@animations.es5.js:534 DebugRenderer2.setProperty@core.es5.js:13740 setElementProperty@core.es5.js:9401 checkAndUpdateElementValue@core.es5.js:9320 checkAndUpdateElementInline@core.es5.js:9254 checkAndUpdateNodeInline@core.es5.js:12337 checkAndUpdateNode@core.es5.js:12284 debugCheckAndUpdateNode@core.es5.js:13141 debugCheckRenderNodeFn @ core.es5.js:13120 (匿名)@ ProfileComponent.html:8 debugUpdateRenderer@core.es5.js:13105 checkAndUpdateView@core.es5.js:12256 callViewAction@core.es5.js:12599 execEmbeddedViewsAction@core.es5.js:12557 checkAndUpdateView@core.es5.js:12252 callViewAction@core.es5.js:12599 execEmbeddedViewsAction@core.es5.js:12557 checkAndUpdateView@core.es5.js:12252 callViewAction@core.es5.js:12599 execComponentViewsAction@core.es5.js:12531 checkAndUpdateView@core.es5.js:12257 callViewAction@core.es5.js:12599 execEmbeddedViewsAction@core.es5.js:12557 checkAndUpdateView@core.es5.js:12252 callViewAction@core.es5.js:12599 execComponentViewsAction@core.es5.js:12531 checkAndUpdateView@core.es5.js:12257 callViewAction@core.es5.js:12599 execEmbeddedViewsAction@core.es5.js:12557 checkAndUpdateView@core.es5.js:12252 callViewAction@core.es5.js:12599 execComponentViewsAction@core.es5.js:12531 checkAndUpdateView@core.es5.js:12257 callWithDebugContext@core.es5.js:13467 debugCheckAndUpdateView@core.es5.js:13007 ViewRef_.detectChanges@core.es5.js:10174 (匿名)@core.es5.js:4812 ApplicationRef_.tick@core.es5.js:4812 (匿名)@core.es5.js:4684 ZoneDelegate.invoke@zone.js:388 onInvoke@core.es5.js:3890 ZoneDelegate.invoke@zone.js:387 Zone.run@zone.js:138 NgZone.run@core.es5.js:3821 下一个@core.es5.js:4684 schedulerFn@core.es5.js:3635 SafeSubscriber.tryOrUnsub @Subscriber.js:238 SafeSubscriber.next@Subscriber.js:185 订阅者._next @订阅者.js:125 订阅者.next @订阅者.js:89主题.下一个@主题.js:55 EventEmitter.emit@core.es5.js:3621 checkStable@core.es5.js:3855 onLeave@core.es5.js:3934 onInvokeTask@core.es5.js:3884 ZoneDelegate.invokeTask@zone.js:420 Zone.runTask@zone.js:188 ZoneTask.invokeTask@zone.js:496 invokeTask@zone.js:1540 globalZoneAwareCallback @ zone.js:1566 错误(异步)
customScheduleGlobal@zone.js:1666 ZoneDelegate.scheduleTask@zone.js:407 onScheduleTask@zone.js:297 ZoneDelegate.scheduleTask@zone.js:401 Zone.scheduleTask@zone.js:232 Zone.scheduleEventTask@zone.js:258 (匿名)@ zone.js:1831 (匿名)@ http.es5.js:1274 Observable._trySubscribe@Observable.js:171 Observable.subscribe@Observable.js:159 ConnectableObservable.connect@ConnectableObservable.js:39 RefCountOperator.call@ConnectableObservable.js:108 Observable.subscribe@Observable.js:156 AuthService._handleResponse@auth.service.ts:592 AuthService.request@auth.service.ts:574 AuthService.get@auth.service.ts:498 PhotoService.getPhotos@photo.service.ts:15 ProfileComponent.loadPhotos@profile.component.ts:78 ProfileComponent.ngOnInit @ profile.component.ts:62 checkAndUpdateDirectiveInline@core.es5.js:10843 checkAndUpdateNodeInline@core.es5.js:12341 checkAndUpdateNode@core.es5.js:12284 debugCheckAndUpdateNode@core.es5.js:13141 debugCheckDirectivesFn@core.es5.js:13082 (匿名)@ ProfileComponent_Host.html:1 debugUpdateDirectives @ core.es5.js:13067 checkAndUpdateView@core.es5.js:12251 callViewAction@core.es5.js:12599 execEmbeddedViewsAction@core.es5.js:12557 checkAndUpdateView@core.es5.js:12252 callViewAction@core.es5.js:12599 execComponentViewsAction@core.es5.js:12531 checkAndUpdateView@core.es5.js:12257 callViewAction@core.es5.js:12599 execEmbeddedViewsAction@core.es5.js:12557 checkAndUpdateView@core.es5.js:12252 callViewAction@core.es5.js:12599 execComponentViewsAction@core.es5.js:12531 checkAndUpdateView@core.es5.js:12257 callWithDebugContext@core.es5.js:13467 debugCheckAndUpdateView@core.es5.js:13007 ViewRef_.detectChanges@core.es5.js:10174 (匿名)@core.es5.js:4812 ApplicationRef_.tick@core.es5.js:4812 (匿名)@core.es5.js:4684 ZoneDelegate.invoke@zone.js:388 onInvoke@core.es5.js:3890 ZoneDelegate.invoke@zone.js:387 Zone.run@zone.js:138 NgZone.run@core.es5.js:3821 下一个@core.es5.js:4684 schedulerFn@core.es5.js:3635 SafeSubscriber.__tryOrUnsub@Subscriber.js:238 SafeSubscriber.next@Subscriber.js:185 订阅者._next @订阅者.js:125 订阅者.next @订阅者.js:89主题.下一个@主题.js:55 EventEmitter.emit@core.es5.js:3621 checkStable@core.es5.js:3855 onHasTask@core.es5.js:3903 ZoneDelegate.hasTask@zone.js:441 ZoneDelegate._updateTaskCount @ zone.js:461 Zone.updateTaskCount @ zone.js:285 Zone.runTask @ zone.js:205 drainMicroTaskQueue @ zone.js:595 Promise.then (async)
scheduleMicroTask@zone.js:578 ZoneDelegate.scheduleTask@zone.js:410 Zone.scheduleTask@zone.js:232 Zone.scheduleMicroTask@zone.js:252 scheduleResolveOrReject @ zone.js:862 ZoneAwarePromise.then @ zone.js:962 PlatformRef
.bootstrapModuleWithZone @ core.es5.js:4537 PlatformRef.bootstrapModule@core.es5.js:4522 (匿名)@main.ts:11 ./src/main.ts@main.bundle.js:1057 __webpack_require
@ inline.bundle.js:55 0 @ main.bundle.js:1065 webpack_require @ inline.bundle.js:55 webpackJsonpCallback @ inline.bundle.js:26 (匿名)@main.bundle.js:1

我做错了什么?

photo.service.ts:

import {Injectable} from '@angular/core';
import {Photo} from '../../models/photo.model';
import {handleError} from "../../shared/functions";
import { AuthService } from '../auth/auth.service';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class PhotoService{
    constructor(
        private _authService:AuthService
    ){ 
    }

    getPhotos(){
        return this._authService.get('photos')
            .map(result => result.json())  
    }

}

photo.component.ts:

import { Component, OnInit} from '@angular/core';
import { AuthService } from "../../../services/auth/auth.service";
import { PhotoService} from "../../../services/photo/photo.service";
import { Photo} from "../../../models/photo.model";

@Component({
  selector: 'photo',
  templateUrl: './photo.component.html',
  styleUrls: ['./photo.component.scss'],
  providers: [PhotoService]
})

export class PhotoComponent implements OnInit {

  photos: Array<Photo>;

  filteredPhotos =[];

  constructor(
    protected authService:AuthService,
    private servPhoto: PhotoService
    ) {}

  ngOnInit() {
    this.loadPhotos();
  }

  private loadPhotos() {
    let filteredPhotos;
    if (this.servPhoto) {
      this.servPhoto.getPhotos().subscribe(
        photo => {
          if(!this.authService.currentUserData) {    
            return; 
          }
          this.photos = photo;
          this.filteredPhotos = this.photos.filter(
            (photo) => photo.users_id ==  this.authService.currentUserData.id
          );
        }
      );
    }
  }

}

照片.model.ts:

export class Photo{
    constructor(
        public users_id: number,
        public photo: Blob
    ) { }
}

photo.component.html:

<div class="container-fluid" *ngIf="authService.currentUserData">
   <img class="img" *ngFor="let photo of filteredPhotos" src="{{ photo.photo }}">
</div>

这是 JSON 本身:

[{"users_id":36,"photo":"/photos/original/missing.png"},

{"users_id":1,"photo":"/photos/original/missing.png"},

{"users_id":1428,"photo":"/photos/original/missing.png"}]

【问题讨论】:

  • 你也可以发布 angular.json 或 angular-cli.json 文件吗?
  • @Sanoj_V 发布
  • 请检查我已经发布了一个答案看看那里
  • 404 表示找不到文件。您没有获得照片的正确 URL。也许尝试在 JSON 中的源代码之前添加 assets,CLI 通常会在您创建新项目时创建一个资产文件夹。

标签: angular typescript


【解决方案1】:

你有src="{{ photo.photo }},你的JSON有"photo":"/photos/original/missing.png"

您的错误:GET http://localhost:4200/photos/original/missing.png 404 (Not Found) 只是告诉您照片不存在。

我做错了什么?

没有错误。该代码只是试图加载不存在的图像。如果您希望 404 消失,请确保 JSON 提供的上述 url 中存在图像。

【讨论】:

  • 但是那里有一张图片
【解决方案2】:

我认为您的服务正在提供 json,而您的课程需要 Blob 数据类型。

【讨论】:

【解决方案3】:

试试这样:

如果您在filteredPhotos 中得到正确回复

<div *ngIf="authService.currentUserData">
<div class="container-fluid" *ngFor="let photo of filteredPhotos" >
   <img class="img"  [src]="photo.photo">
</div>
</div>

【讨论】:

  • 您是否以文件形式收到响应?? localhost:4200/photos/original/missing.png??
  • 所以问题是您没有在系统上下载文件
  • 我得到的答案是“text/html”
  • 应该是“image/png”
  • 我不明白“所以问题是您没有在系统上下载文件”
【解决方案4】:

您需要在 angular.jsonangular-cli.json 文件中找到文件夹。

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "frontend"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico",
        "photos"   //<==== you have to add this folder source here     
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "../node_modules/bootstrap/dist/css/bootstrap.css",
        "../node_modules/font-awesome/css/font-awesome.min.css",
        "../node_modules/perfect-scrollbar/css/perfect-scrollbar.css",
        "./assets/sass/material-style.scss",
        "./assets/css/style.css",
        "../node_modules/primeicons/primeicons.css",
        "../node_modules/primeng/resources/themes/omega/theme.css",
        "../node_modules/primeng/resources/primeng.min.css",
        "../node_modules/quill/dist/quill.core.css",
        "../node_modules/quill/dist/quill.snow.css"
      ],
      "scripts": [
        "../node_modules/jquery/dist/jquery.js",
        "../node_modules/quill/dist/quill.js",
        "../node_modules/bootstrap/dist/js/bootstrap.js",
        "../node_modules/bootstrap-material-design/dist/js/ripples.min.js",
        "../node_modules/bootstrap-material-design/dist/js/material.min.js",
        "../node_modules/arrive/src/arrive.js",
        "../node_modules/chart.js/dist/Chart.js",
        "../node_modules/moment/moment.js",
        "../node_modules/perfect-scrollbar/dist/perfect-scrollbar.min.js",
        "../node_modules/bootstrap-notify/bootstrap-notify.js",
        "../node_modules/hammerjs/hammer.min.js"
      ],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "src/tsconfig.spec.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "e2e/tsconfig.e2e.json",
      "exclude": "**/node_modules/**"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {
    }
  },
  "warnings": {
    "typescriptMismatch": false
  }
}

然后停止您的 ngnpm 并再次运行。

现在 ng servenpm start 这解决了你的问题

【讨论】:

  • @user10254427 你检查了吗??
猜你喜欢
  • 1970-01-01
  • 2022-12-22
  • 2020-11-22
  • 2010-11-16
  • 1970-01-01
  • 1970-01-01
  • 2013-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多