angular2 http.post 方法抛出 typeerror{} 异常

angular2 http.post method throws typeerror{} exception

我试图根据需要将现有的 angularjs 库更改为 angular2。 http.post 下面代码中的方法将 TypeError {} 作为异常抛出。有人请帮忙,因为我坚持这一点。

login() {
  return new Promise((resolve, reject) => {
    if(typeof jsSHA !== "undefined") {
      var signatureObj = (new OauthUtility()).createSignature("POST", this.magentoOptions.baseUrl+"/oauth/initiate", this.oauthObject, {oauth_callback: "http://localhost/callback"}, this.magentoOptions.clientSecret, null);                                   
      let headersInitiate = new Headers();
      headersInitiate.append('Authorization',signatureObj.authorization_header);
      headersInitiate.append('Content-Type','application/x-www-form-urlencoded');
      let url = this.magentoOptions.baseUrl + "/oauth/initiate";
      let callback = "oauth_callback=http://localhost/callback";

      try{
        this.http.post(url, callback,{headers: headersInitiate})
         .subscribe(
          (result) => {
          console.log("i am inside");
          var rParameters = (result).split("&");
                            .....
      }
      catch(Exception){
        console.log(Exception)
      }

你应该尝试这样的事情:

var signatureObj = (new OauthUtility()).createSignature("POST", 
     this.magentoOptions.baseUrl+"/oauth/initiate", this.oauthObject,
     {oauth_callback: "http://localhost/callback"},
     this.magentoOptions.clientSecret, null);    let headersInitiate = new Headers();

headersInitiate.append('Authorization',
          signatureObj.authorization_header);
headersInitiate.append('Content-Type',
          'application/x-www-form-urlencoded');
let url = this.magentoOptions.baseUrl + "/oauth/initiate";

let payload = ' ... ';
this.http.post(url, payload,{headers: headersInitiate})
    .subscribe(
      (result) => {
        console.log("i am inside");
        var rParameters = (result).split("&");
        (...)
      });

以下是我对您的代码的评论:

  • post 方法的第二个参数应该是对应于负载的字符串而不是回调。我从你的 headers 看到你想发送 url-encoded 表格,所以你需要自己创建它
  • try catch 不是必需的,因为执行 HTTP 是异步的,错误可能 "catched" 在 subscribe 方法的第二个参数(另一个回调)中。
  • 你根本不需要承诺。对于 HTTP,Angular2 在底层使用 observables。它们也针对异步处理。

修复所有这些后,我认为您不会再有错误了...

希望对你有帮助, 蒂埃里

我发现即使在执行了上述所有步骤后仍然卡住了。完整的解决方案如下。 按照 Thierry 的建议删除 try catch 块和承诺。 在构造函数中使用http的依赖注入定义http.

import {Http,HTTP_PROVIDERS,Headers} from 'angular2/http';
import {Injector} from "angular2/core";
 constructor() {

        var injector = Injector.resolveAndCreate([HTTP_PROVIDERS]);
        this.http = injector.get(Http);
}