簡體   English   中英

如何將響應從服務傳遞到組件?

[英]How to pass a response from service to component?

我試圖將響應從我的服務傳遞到組件,以便可以在html頁上顯示它,但我不知道如何。

組件

uploadFile(): void {

  this.errors = null;

  let file = this.fileInput.nativeElement;
  if (file.files && file.files[0]) {
    let fileToUpload = file.files[0];
    this.getInfoService
      .uploadImage(fileToUpload)
      .subscribe(
        response => { console.log(response) },
        err => {
          //this.errors = err._body
          this.errors = err.json().image
          console.log("ERR", err.json().image)
        },
        () => console.log("()",'worked')
      );
  }

}

編輯:問題是在我的服務。 這是工作代碼。

uploadImage(fileToUpload: any) : Observable<any> {

  let input = new FormData();
  input.append("image", fileToUpload);
  return this.http.post('http://Api.app/api/v1/upload', input)
    .map(
      (response: Response) =>  {
        // I was missing this part
        response.json()
      }
    );
}

在組件上創建幾個屬性,然后將響應數據分配給這些屬性。

image: any;
message: string;

uploadFile(): void {

  this.errors = null;

  let file = this.fileInput.nativeElement;
  if (file.files && file.files[0]) {
    let fileToUpload = file.files[0];
    this.getInfoService
      .uploadImage(fileToUpload)
      .subscribe(
        response => { 
            this.image = response.image;
            this.message = response.message;
       },
        err => {
          //this.errors = err._body
          this.errors = err.json().image
          console.log("ERR", err.json().image)
        },
        () => console.log("()",'worked')
      );
  }
}

要在您的視圖中顯示消息:

{{ message }}

要顯示嵌入式圖像,您需要查看以下文章:

Angular2顯示嵌入式圖像

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM