繁体   English   中英

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

[英]Access http.post() response data from outside the method in Angular 2

我创建了一种添加新项的方法, 新增活动页面

其中包括s图片上传,为此,我创建了另一个方法(upload())并上传了图片文件,并获得了文件名作为响应,我想将文件名和表单详细信息作为post( )提交到Submit()方法中。现在的问题是,无法通过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 method()访问this.imagename

在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;
        },
    ):
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM