Access http.post() response data from outside the

2019-09-14 23:02发布

问题:

I have create one method to add new item ,

Which include s image upload,for that i have create another method(upload()) and uploaded the image file and get the name of the file as the response,and i want to pass the name of the file and form details as post() request in submit() method.Now the problem is ,the name of the file as response of file upload cannot be accessed from the submit() method.

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

I want to access this.imagename from Onsubmit method().

回答1:

In demo-service .ts file

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

}

In Component:

myVar;
constructor(private demoService: DemoService ){
}

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


标签: angular