【问题标题】:How to correctly write a service and upload an image to Angular 2?如何正确编写服务并将图像上传到 Angular 2?
【发布时间】:2018-08-14 16:03:22
【问题描述】:

我有这个模型:

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

还有这样的服务:

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(res => res.blob())
            .map(blob => URL.createObjectURL(blob))
            .toPromise();  
    }


}

这里是授权用户过滤器上传的图片:

  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.user_id);
        });
    }
  }

我得到这样一个错误:

/home/admin/Desktop/project/frontend/src/app/layout/pages/profile/profile.component.ts 中的错误 (79,36): 类型上不存在属性“订阅” '承诺'。

告诉我如何正确实现下载。

【问题讨论】:

    标签: angular


    【解决方案1】:

    使用thengetPhotos 返回一个承诺而不是可观察的。所以你不能在 promise 上使用 subscribe 关键字。

    this.servPhoto.getPhotos().then(photo => {
    

    【讨论】:

    • 该死,因为出现了这个其他错误Error: Uncaught (in promise): Error: The request body isn't either a blob or an array buffer
    【解决方案2】:

    下载图片:

    组件.ts

    /**
     * Method is used to view or download the file
     */
    getPhotos() {
        this.fileService.getImage(url, type).subscribe(respData => {
            this.downLoadFile(respData, this.type);
        }, error => {
           console.log(error)
        });
    }
    
    
       /**
         * Method is use to download file.
         * @param data - Array Buffer data
         * @param type - type of the document.
         */
        downLoadFile(data: any, type: string) {
            var blob = new Blob([data], { type: type.toString() });
            var url = window.URL.createObjectURL(blob);
            var pwa = window.open(url);
            if (!pwa || pwa.closed || typeof pwa.closed == 'undefined') {
                alert('Please disable your Pop-up blocker and try again.');
            }
        }
    

    service.ts

    getImage(url:string,type:string){
            let headers = new HttpHeaders().append("Authorization", "Bearer " + .token)
            return this.httpClient.get(url, {responseType: 'arraybuffer',headers:headers});
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-18
      • 2017-12-29
      • 2016-10-23
      • 1970-01-01
      • 1970-01-01
      • 2015-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多