在Angular 2中将字节数组内容加载到浏览器

时间:2018-08-09 13:43:59

标签: c# asp.net angular

我正在使用ASP.Net Web API进行Angular 4项目,并尝试以PDF形式在浏览器中加载字节数组内容。我从我的ASP.Net Web API返回了一个具有字节数组的HttpResponseMessage,但是我没有在客户端得到响应。这是我的代码-

Server side (C#)    
var response = new HttpResponseMessage();
var stream = new MemoryStream(offerLetterPdfByte);
//offerLetterPdfByte is the byte array of a dynamically created pdf document
response.StatusCode = HttpStatusCode.OK;
response.Content = new ByteArrayContent(stream.ToArray());

Angular Code in Component
public PreviewOfferLetter() {
    const editorContentHtml = this.frmReviewOfferLetter.controls["EditorNote"].value;
    this._humanResourceService.PreviewCandidateOfferLetter(editorContentHtml).subscribe(
      data => {
        const file = new Blob([data], {type: "application/pdf"});
        const fileUrl = URL.createObjectURL(file);
        window.open(fileUrl);
      },
      error => {
        console.log(error);
      },
      () => {

      });
  }

//Method In Service
public PreviewCandidateOfferLetter(offerLetterHtml: any): Observable<any>{
    return this._httpHelperService.ExecutePostRequest(ApiUrlConfig.HumanResource.PreviewCandidateOfferLetter, offerLetterHtml);
  }

服务器端方法的类型为HttpPost,执行效果非常好。在调试服务器代码时,我能够看到字节数组,但是响应未到达组件中的数据部分,它总是命中错误部分,并且错误对象如下-

 error = Object {StatusCode: undefined, Message: undefined}

//Service Code
public ExecutePostRequest(endpoint: any, params?: any, customErrorCallback?: any): Observable<any> {
      this._requestOptions = new RequestOptions({
          method: RequestMethod.Post,
          url: this.baseUrl + endpoint,
          headers: this.headers,
          body: JSON.stringify(params),
          withCredentials: true
      });
      this._loggerService.Log("info", "Execute Request : " + this.baseUrl + endpoint, null, "HttpHelperService", "executeRequest", params);
      return this._http.request(new Request(this._requestOptions)).map(this.ExtractData).catch(customErrorCallback !== undefined ? customErrorCallback : this.HandleError);
    }

请建议我做错了。预先感谢。

0 个答案:

没有答案