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

Creating TypeScript versions of `delegate` pattern JavaScript code

Looking for a way to convert the following javascript code into typescript? const handlers = { say (msg) { console.log(msg) }, add (a, b) { return a + b } } function caller (method, ...args) { if (handlers[method]) return handlers[methd ...

What is the best way to close ngx-simple-modal in angular7 when clicking outside of the modal component?

Can anyone help me with closing the modal in my angular7 app when the user clicks outside of the modal component? I have been using the ngx-simple-modal plugin, and I tried implementing the following code: this.SimpleModalService.addModal(LinkPopupCompone ...

Monitor the number of ng-repeat items altering within a directive

I am using the angular-sly-carousel directive to display some data. The data is dynamically added as the user scrolls down, so I need to reload the sly carousel options after scrolling. Is there a way to detect when the length of ng-repeat elements change ...

Enhance your file uploading capabilities with Protractor and dropzonejs

I'm new to using protractor and I have a project that involves testing with Angular and dropzonejs for file uploads. Although I've come across some information on how to upload files with protractor, I am struggling to figure out how to do so wit ...

Ways to incorporate environment variable in import statement?

In my Angular v5 project, I have a situation where I need to adjust the import path based on the environment. For example, I have an OwnedSetContractABI file located in different folders for each environment - dev and production. In dev environment, the ...

Acquiring the asset within the controller

Having trouble accessing my service within the controller. This project was generated with the latest yeoman which handles template creation and file merging during build. Whenever I make changes, Angular stops working without displaying any errors in the ...

Interactive Tab content display

I'm working on a tabs component and I need Angular to only render and initialize the active tab instead of all tabs. Is there a way to achieve this? <my-tabs> <my-tab [tabTitle]="'Tab1'"> <some-component></some-co ...

Is it feasible to connect to an output component without using EventEmitter?

When it comes to creating components, I've found it quite easy to use property binding for inputs with multiple options available like input(). However, when dealing with component outputs, it can be a bit complicated as there's only one option u ...

Conditional ngOptions in AngularJS allows you to dynamically update the options

Currently, I am working with a select box that iterates through an array of departments to identify eligible parent departments. <select class="editSelectBox" ng-model="dept.parentDepartment" ng-options="dept as dept.name for dept in depts track by de ...

Exploring the functionality of transitioning between pages in AngularJS with a single click within a text box

Here is my JavaScript code: var todoModule = angular.module('ToDoModule', ['ngRoute','ngTable']) .config(function($routeProvider) { $routeProvider // route ToDo page .when('/', { ...

Can one verify if an Angular application currently has active app modules running?

I am developing a unique plugin for Angular that is designed to automatically initialize an Angular app module if none are found. However, if there is already a running or declared ng-app, my plugin will utilize that existing module instead. Here is an i ...

The npm script for running Protractor is encountering an error

Currently, I am facing an issue while trying to execute the conf.js file using an npm script. The conf.js file is generated within the JSFilesRepo/config folder after running the tsc command as I am utilizing TypeScript in conjunction with protractor-jasmi ...

Could someone provide a detailed explanation of exhaustMap in the context of Angular using rxjs?

import { HttpHandler, HttpInterceptor, HttpParams, HttpRequest, } from '@angular/common/http'; import { Injectable } from '@core/services/auth.service'; import { exhaustMap, take } from 'rxjs/operators'; import { Authe ...

retrieve a collection of objects using Angular CLI

Hey there, I'm currently working on fetching data using a get request in Angular. My Apartment class is structured as follows: export class Apartment { id: number; address: string; constructor(id: number, name: string) { this.id = id; ...

To collapse a div in an HTML Angular environment, the button must be clicked twice

A series of divs in my code are currently grouped together with expand and collapse functionality. It works well, except for the fact that I have to click a button twice in order to open another div. Initially, the first click only collapses the first div. ...

Having trouble retrieving the $scope value in HTML, even though it was assigned within the success function of $http.post

Having trouble accessing the values of $scope properties after a successful $http post in index.html file. Here is the code snippet for reference, any help in resolving this issue would be greatly appreciated as I am new to AngularJs var app = angular.m ...

Modify the standard localStorage format

I'm encountering a dilemma with my two applications, located at mysite.com/app1 and mysite.com/app2. Both of these apps utilize similar localStorage keys, which are stored directly under the domain "mysite.com" in browsers. This setup results in the l ...

Error Encountered: Angular 2 ngOnInit Method Being Executed Twice

Encountered an unusual error in Angular 2 while working on two components that share similarities in templates and services. Here is a breakdown of how they function: Component: data: any; constructor(private _service: TheService) {} ngOnInit() { t ...

Controller encounters a error when requiring a module

Struggling to set up Stripe for my app, I've encountered some issues with the module implementation. Typically, I would require a module at the top of the file to use it. However, in the paymentCtrl file, when I do this, it doesn't work and I rec ...

Ways to transfer specific properties from one object to another in TypeScript

I'm currently working on a function that selectively copies key-value pairs from one object to another in order to remove certain properties. The code snippet for this function is shown below: sanitizeData: function (sourceObject: object, ...allowedKe ...