I have been facing an issue where I am attempting to click a button on an HTML page to trigger a TypeScript function called `getToken()`. Strangely, the function does not seem to get executed when the button is clicked. Surprisingly, I have tested the `getToken()` function separately by calling it from within the constructor, and it works perfectly fine without any errors or warnings being displayed in the browser's Console.
Below is the snippet of code from `app.module.ts` that contains the `getToken` method I am trying to invoke from the HTML file:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HttpModule } from '@angular/http';
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { RequestOptions, Request, RequestMethod } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@NgModule({
imports: [ BrowserModule, HttpModule ],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
@Injectable()
export class AppModule {
constructor(private http: Http) {}
private _token: string;
public getToken() {
let url = "https://my.domain.net/oauth/token";
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('grant_type', 'password');
urlSearchParams.append('username', 'myUserName');
urlSearchParams.append('password', 'myPassword');
let body = urlSearchParams.toString()
this.http.post(url, body)
.map(res => res.json())
.subscribe(
data => { this._token = data.access_token; alert("TOKEN: " + this._token); console.log(data); },
err => console.log(err),
() => console.log('Fetching complete for Server Metrics')
);
}
}
This is how I am trying to call the TypeScript function in the HTML file:
<button (click)="getToken()">Get Token</button>