Http.post Angular 2有时执行,有时不执行。

时间:2017-06-27 22:26:03

标签: typescript angular2-services http-response-codes

我做错了什么?

该方法返回this.http.post(this.OauthLoginEndPointUrl,               params.toString(),opts)有时会被触发,有时则不会触发。 我没有错误也没有结果 有人知道如何解决这个问题吗?

import { Injectable } from '@angular/core';
import { Http, Headers, Response, URLSearchParams, RequestOptionsArgs } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/catch'

@Injectable()
export class AuthenticationService {

  private OauthLoginEndPointUrl = 'https://southwestsolutions.no/app_test/rest/v2/oauth/token';  // Oauth Login EndPointUrl to web API
  private clientId = 'client';
  private clientSecret = 'secret';
  private username;
  private password;

  constructor(private http: Http) { }

  login(username: string, password: string) {

    const params = new URLSearchParams();
    params.append('grant_type', 'password' );
    params.append('username', username );
    params.append('password', password );

    const val = this.clientId + ':' + this.clientSecret;
     console.log(btoa(val));

    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    headers.append('Authorization', 'Basic ' + btoa(val));
    const opts: RequestOptionsArgs = {headers};

       console.log(params);

        return this.http.post(this.OauthLoginEndPointUrl,
          params.toString(), opts)
            .map((response: Response) => {
                // login successful if there's a jwt token in the response
                const user = response.json();

                if (user && user.token) {
                    // store user details and jwt token in local storage to keep user logged in between page refreshes
                    localStorage.setItem('currentUser', JSON.stringify(user));
                }

                return user;
            })
            .catch((error) => Observable.throw(error.json().error || 'Server error'));
    }

    logout() {
        // remove user from local storage to log user out
        localStorage.removeItem('currentUser');
    }
}

0 个答案:

没有答案