如何正确编写服务并将图像上传到Angular 2?

时间:2018-08-14 05:58:51

标签: angular

我有这个模型:

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):类型上不存在属性“ subscribe”   “承诺”。

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

2 个答案:

答案 0 :(得分:0)

使用thengetPhotos返回一个承诺,而不是可观察的。因此您不能在承诺中使用subscribe关键字。

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

答案 1 :(得分:0)

要下载图像:

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