【问题标题】:Service isn't firing off post request in Angular 4.x服务未在 Angular 4.x 中触发发布请求
【发布时间】:2019-01-23 05:49:43
【问题描述】:

我在服务中具有以下功能uploadCSV,该服务应该发布到端点以上传 csv - 我可以在控制台日志中看到 csv 文件在那里但是在检查网络选项卡时没有任何 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]);
}

}

【问题讨论】:

  • 不订阅帖子通话?

标签: angular http post angular-services


【解决方案1】:

Observables 是惰性的,你需要订阅它才能执行。

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

【讨论】:

    【解决方案2】:

    您需要像this 示例中那样订阅http post call:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-07
      • 2018-12-23
      • 2020-10-01
      • 1970-01-01
      • 2020-09-17
      • 2016-09-29
      • 1970-01-01
      相关资源
      最近更新 更多