Greetings and good afternoon to everyone. I hope you all are doing well.
I am a beginner in AngularJS, currently using Visual Studio, Ionic 2, and TypeScript.
I have successfully connected my app to a REST API in .NET and have implemented a token for testing purposes using Microsoft.Owin.Security.OAuth. Previously, I created the token in Xamarin and it worked flawlessly. Now, attempting to do the same with AngularJS using the following code:
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('Success!');
} else {
this.jsonresult = 'Error fetching token.';
console.log('Error!');
}
});
return (this.jsonresult);
}
The objective is to retrieve the token string using this function. However, the issue is that it fails and goes into the "else" condition. Another concern is regarding the function's return value. Even though I have set a message in the variable, it does not return any content in another class - instead, it returns as "undefined".
In the other class, I have included it like this:
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);
}
I have conducted extensive research before resorting to seeking help through questions but have been unable to resolve the issue.
As a newcomer to this field, I acknowledge that the solution likely involves a trivial detail.
The token type in use is "Bearer".
Thank you in advance for any assistance provided. Best regards, Amanda Marins.