Utilizando Typescript com Ionic 2 e AngularJS para autenticar através de um método de post na requisição HTTP e

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.

Answer №1

Successfully resolved the following:


TokenValidate Class

>constructor(public http: Http) {
>  this.http = http;
>}
>
>public RetrieveValidatedToken (credentials: string){
>    this.urlToken = 'http://localhost:63634/Token';
>   
>
>    var header = new Headers();
>    header.append('Content-Type', 'application/x-www-form-urlencoded');
>            
>    this.http.post(this.urlToken, credentials,{ headers: header })
>      .subscribe(res => {
>      this.result = res.json();
>    localStorage.setItem('token',this.resultado.access_token);            
>    });
>
>    this.jsonresult = localStorage.getItem('token');
>    //console.log(this.jsonresult);
>
>    return
>        ( this.jsonresult );
>}

UserService Class

>constructor(public http: Http, public tokenValid: TokenValidate){
>    this.http = http;
>    this.headers = new Headers ({'Content-Type': 'application/json',
>      'Accept': 'q = 0.8; application/json; q = 0.9'});
>    this.creds = "grant_type=password" + "&username=User" 
>        +"&password=user1234-";
>    this.token = this.tokenValid.RetrieveValidatedToken (this.creds);
>    console.log ('Bearer Token:' + this.token);
>    this.headers.append ('Authorization', 'Bearer' + this.token);
>            
>    this.options = new RequestOptions({headers: this.headers});
>}
>
>getUsers(){
>    if (this.data){
>       return Promise.resolve(this.data);
>    }
>       
>    return new Promise(resolve => {
>        this.http.get (this.apiUrl+'/user', this.options)
>         .map(res => res.json())
>         .subscribe(data => {
>             this.data = data;
>             solve(this.data);
>         });
>    });
>}

Hope this is beneficial for those in need.

Thank you!! =)

Sincerely Amanda Marins.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps to resolve the issue of being unable to destructure property temperatureData from 'undefined' or 'null' in a React application without using a class component

CODE: const { temperatureData } = state; return ( <> <div className="flex flex-row"> {temperatureData.map((item, i) => ( <div className="flex flex-auto rounded justify-center items-center te ...

Dealing with Header Issues in Express: Avoiding Sending Headers Multiple Times!

Encountering an issue with express while working on this code: appToken.post('/getToken', function(req, res) { console.log("Received a request to generate a token"); console.log("Cookie : "+req.headers.cook ...

What is the best way to transfer variables in my specific scenario?

As I consider the optimal approach for managing my controllers, I find myself faced with a challenge of passing data between them. In my setup, I have multiple controllers that require sharing data throughout. For the first controller: app.controller(&a ...

A Project built with React and TypeScript that includes code written in JavaScript file

Is it an issue when building a React project with Typescript that includes only a few JS components when moving to production? ...

Using AngularJS to iterate through JSON data

I received JSON data from my Facebook account and saved it in a file called facebook.json. Next step is to retrieve and process the data from the JSON file in my controller. app.controller('Ctrl', function($scope, $http) { $http({metho ...

Get the GET parameters without changing the '+' sign to "" ""

One of the API providers I work with sends me a unique token in its responses. The token is typically in this format: SomE73ThiL1k3T+ashR To send this token from my AngularJS front end to my Django back end using $resource, I do the following: var res = ...

Place the Div in a consistent position on images of varying widths

I have a dilemma with my class that is supposed to display images. The issue arises when I try to place a div within an image inside this class. Everything works smoothly when the image takes up the entire width of the class, but as soon as the image widt ...

The controller does not modify the value stored in the fullName variable

<!DOCTYPE html> <html > <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <script> var app= angular.module('myApp',[]); app.controller('myController',function($sco ...

NestJs encountering issues with reading environment variables

I used the instructions from the Nest documentation to set up the configuration, however, it's not functioning correctly. app.module.ts @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true }), TypeOrmModule.forRoot(config), AuthMo ...

An object in typescript has the potential to be undefined

Just starting out with Typescript and hitting a snag. Can't seem to resolve this error and struggling to find the right solution useAudio.tsx import { useEffect, useRef } from 'react'; type Options = { volume: number; playbackRate: num ...

Creating a dynamic type class in TypeScript that can inherit characteristics from another class

Can a wrapper class be designed to dynamically inherit the properties of another class or interface? For instance... interface Person { readonly firstName: string; readonly lastName: string; readonly birthday?: Date } class Wrapper<T> { ...

Issues with Angular $http service retrieving data from a .JSON file

Below is the code snippet for my http service: app.controller('StoreController', ['$http', function($http){ var store = this; store.products = []; $http.get('/store-products.json').then(function(data){ sto ...

Tips for altering the label color of an md-input-container after text has been entered

Is there a way to dynamically change the color of an md-input-container label after certain input is added? The default grey color gives the impression that the field is disabled. I specifically want to modify the color of the label "Description" when the ...

Why do referees attempt to access fields directly instead of using getters and setters?

I am facing an issue with my TypeScript class implementation: class FooClass { private _Id:number=0 ; private _PrCode: number =0; public get Id(): number { return this._Id; } public set Id(id: number) { this._Idprod ...

Customize ion-icon within a Tab button using ng-class in Ionic AngularJS

I'm struggling to update the icon on Tab from "ion-social-google-outline" to "ion-social-google" once it's clicked, but I haven't been able to crack the code... Because I need to navigate within an ion-slide-box, I can't utilize ion-ta ...

Error: The variable "Tankvalue" has not been declared

Is there a way to fix the error message I am receiving when trying to display response data in charts? The Tankvalue variable seems to be out of scope, resulting in an "undefined" error. The error message states that Tankvalue is not defined. I need to ...

What allows mapped types to yield primitive outputs when using {[P in keyof T]}?

Check out this innovative mapped type example that utilizes the power of keyof: type Identity<T> = { [P in keyof T]: T[P]; }; Have you ever wondered why Identity<number> results in the primitive number type, rather than an object type? Is th ...

Struggling to overcome the TS2322 error when assigning generic values

I am currently working on developing higher-order React components that will include default values for components labeled as "named". Here is a basic implementation example: type SomeProps = { a: string } type Variants = 'variantA' | 'var ...

How can we fetch data from the server in Vue 2.0 before the component is actually mounted?

Can anyone help me with this question noted in the title? How can I prevent a component from mounting in <router-view> until it receives data from the server, or how can I fetch the data before the component is mounted in <router-view>? Here a ...

How to trigger an Angular JS route without loading a view

Could someone help me with calling the /auth/logout url to get redirected after a session is deleted? app.config(['$routeProvider',function($routeProvider) { $routeProvider .when('/auth/logout',{ controller:'AuthLo ...