【发布时间】:2018-02-18 11:00:53
【问题描述】:
首先祝大家下午好,希望你没事。
我是 AngularJS 的新手。我正在使用 Visual Studio、Ionic 2 和 typescript。
我已经设法用 .net 中的 REST api 为我的应用程序提供服务,现在我已经实现了一个用于测试的令牌。它是 Microsoft.Owin.Security.OAuth ... 在我在 Xamarin 中制作令牌之前它起作用了。现在我通过 Angularjs 尝试以下方法:
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Storage } from '@ionic/storage';
import { URLSearchParams } from "@angular/http";
import 'rxjs/add/operator/map';
import 'rxjs/Rx';
public GetValidatedToken(){
this.urlToken = 'http://localhost:63634/token';
this.headers = new Headers();
this.headers.append('Content-Type', 'application/x-www-form-urlencoded');
// this.data = 'grant_type=password&username=' + 'User' + '&password=' + 'user1234-';
// this.data = "grant_type=password" + "&username=User" + "&password=user1234-";
this.urlSearchParams = new URLSearchParams();
this.urlSearchParams.append('grant_type', 'password');
this.urlSearchParams.append('username', 'User');
this.urlSearchParams.append('password', 'user1234-');
this.data = this.urlSearchParams.toString();
this.http.post('http://localhost:63634/token', this.data, { headers: this.headers })
.subscribe(res => {
if (res.json().success) {
window.localStorage.setItem('token', res.json());
this.jsonresult = window.localStorage.getItem('token');
console.log('Sucesso!');
} else {
this.jsonresult = 'Erro ao pegar token.';
console.log('Deu erro!');
}
});
return (this.jsonresult);
}
我想用这个函数返回令牌字符串。 错误是它没有成功,它进入了“else”。另一个问题是函数的“结果”。 即使我在变量中放了一条消息,在另一个类中也没有返回内容......它返回“未定义”
在其他类中我是这样说的:
import { TokenValidate } from '../token/TokenValidate';
...
constructor(public http: Http, public tokenValid: TokenValidate, ) {
this.http = http;
this.token = this.tokenValid.GetValidatedToken();
console.log('Token bearer :' + this.token);
}
我做了很多研究,所以我不必提出问题,但它没有用。
请记住,我对此完全陌生,这肯定是一个荒谬的细节
令牌类型为“Bearer”。
提前感谢您的帮助。 阿曼达·马林斯 (Amanda Marins)。
【问题讨论】:
-
欢迎来到 StackOverflow!请只用英文发布问题,否则大多数用户将无法为您提供帮助。
-
感谢@sebaferreras 和 Sonicd300 的提示和帮助! =)
标签: angularjs http typescript ionic2 token