从Angular 2中的方法外部访问http.post()响应数据

时间:2017-06-19 05:51:56

标签: angular

我创建了一个方法来添加新项目Add new event page

其中包括s图像上传,为此我创建了另一种方法(upload())并上传了图像文件并获取文件名作为响应,我想传递文件名和表单详细信息作为submit()方法中的post()请求。现在的问题是,无法从submit()方法访问文件名作为文件上传的响应。

event.component.ts

  onSubmit(f: NgForm) {      //submit method to post event form data
  this.showAddNew = false;
  let testvar =this.upload();
  let add_event_body = {
    "name" : f.value.name,
    "description":f.value.description,
    "start_date":f.value.start_date,
    "start_time":f.value.start_time,
    "end_date":f.value.end_date,
    "end_time":f.value.end_time
   };
  this.addeventService.doAddEvent(add_event_body).subscribe();
}

   upload() {                //Upload method to upload image and get file name as response
    let inputEl: HTMLInputElement = this.inputEl.nativeElement;
    let fileCount: number = inputEl.files.length;
    let formData = new FormData();
    if (fileCount > 0) { // a file was selected
        for (let i = 0; i < fileCount; i++) {
            formData.append('file[]', inputEl.files.item(i));
        }
        this.http
            .post('http://localhost:8080/EventManager/UploadFile', formData).subscribe( data => {

                        this.imagename=data.json().file;
                        console.log(this.imagename);
                        return this.imagename; 
                   },
                    err => 
                        console.log("error")                    
                    )
     }
     console.log(this.imagename);
   }

我想从Onsubmit方法()中访问this.imagename

1 个答案:

答案 0 :(得分:1)

  

在demo-service .ts文件中

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {JsonResponse} from '../models/json-response.model';

@Injectable()
export class DemoService {
protected yourVar

constructor(private http: Http) {
}

fetchData(): Observable<any> {

    return this.http.get('').map(
        (res: Response) => {
            this.yourVar = res.json();
            return this.yourVar;
        }).catch(
        (error: Response) => {
            return Observable.throw(error.json() as JsonResponse);
        });
}

}

  

在组件中:

myVar;
constructor(private demoService: DemoService ){
}

testFunction(): void {
    this.demoService: .fetchData.subscribe(
        (data) => {
           this.myVar=data;
        },
    ):
}