服务未触发Angular 4.x中的发布请求

时间:2018-08-16 09:47:46

标签: angular http post angular-services

我在服务中具有以下功能uploadCSV,该服务应发布到终结点以上传csv-我可以在控制台日志中看到csvfile存在,但是在检查“网络”选项卡时没有任何内容显示了POST请求-为什么有任何想法?

import { Injectable } from '@angular/core';
import { ApiService } from "../../../services/api.service";
import { Observable } from "rxjs/Observable";
import { HttpClient } from '@angular/common/http';


@Injectable()
export class BulkuploadService {

constructor(
    private http: HttpClient,
    private apiService: ApiService,
    private userService: UserService
) { }

uploadCSV(csvFile: any): any {
    console.log(csvFile);
    let formData:FormData = new FormData;
    formData.append('file', csvFile, csvFile.name);
    console.log(formData);

    let url = this.apiService.getApiUrl('bulk-upload/upload');
    console.log(url);

    return this.http.post(url, formData);
}

}

//组件

import { Component, 
OnInit, 
Inject,
Input, 
Output, 
EventEmitter, 
ElementRef } from '@angular/core';

import { DOCUMENT } from '@angular/common';
import * as moment from 'moment';
import { BulkuploadService } from './bulkupload.service';

@Component({
selector: 'app-bulkupload',
templateUrl: './bulkupload.component.html',
styleUrls: ['./bulkupload.component.scss'],
providers: [
    BulkuploadService
]
})
export class BulkuploadComponent implements OnInit {

@Output() closeEvent = new EventEmitter<boolean>();
private postObjects = [];

constructor(@Inject(DOCUMENT) private document: any,
    private ref: ElementRef,
    public bulkService: BulkuploadService    
) { }

uploadCSV(event: any): void {
    this.bulkService.uploadCSV(event.target.files[0]);
}

}

2 个答案:

答案 0 :(得分:1)

您需要订阅http发帖,例如this示例:

showConfig() {
  this.configService.getConfig()
    .subscribe((data: Config) => this.config = {
        heroesUrl: data['heroesUrl'],
        textfile:  data['textfile']
    });
}

答案 1 :(得分:1)

可观察对象是惰性的,您需要订阅它才能执行。

 uploadCSV(event: any): void {
    this.bulkService.uploadCSV(event.target.files[0]).subscribe(data => {
      //handle next steps after execution
    },err=>{
      //handle error
    },()=>{
      //completed
    });
  }