Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a service function from browser console in angular 6

I have just made a few changes to some methods in one of the services, and wanted to see if the changes had worked properly or not, but instead of creating a class and testing them out manually, I wanted to know if there was a way to call the functions in chrome's console.

I had followed this example for implementing a logger service, and added to my already created jwt service below.

Unfortunately I don't have any implementation of the error in the application so I can't really test it directly. I wanted to check if both conditions are working properly. I checked this answer out but when I try it for myself it gives me a null error (maybe because this expects a component and I want to test a service perhaps).

To give an example, here is my class, and a method as an example which I want to test in the console:

Jwt.service.ts

import { Injectable } from '@angular/core';
import { TranslatePipe } from 'src/app/pipes/translate/translate.pipe';
import { LoggerService } from "src/app/services/logger/logger.service";
/**
* Injects the JSON web token service in the project
*/
@Injectable({
  providedIn: 'root'
})

/**
* This service is responsible for management of the jwt token, which would be used
* for authentication/authorization purposes. The service includes methods to save, delete
* and retrieve the token
*/
export class JwtService {


  constructor(
    private translate: TranslatePipe,
    private logger: LoggerService) { }

  /**
   * This method fetches the token from local storage and returns it.
   *
   * @method getToken
   * @return
   */
  getToken(): string {
    var token = window.localStorage['jwtToken'];
    if (token !== undefined) {
      return token;
    } else {
      this.logger.invokeConsoleMethod('error', this.translate.transform("generic[responses][error][token][001]"));
      throw new Error(this.translate.transform("generic[responses][error][token][001]"));
    }
}
like image 642
Muhammad Hamza Avatar asked Jan 16 '19 07:01

Muhammad Hamza


People also ask

How to get a service from the console in angular?

You can get to any service / constant / etc. from the console using an injector instance. Just grab the root element and ask for its injector instance. Usually the document.body has angular application around it, so if you need to grab something angular.element (document.body).injector ().get ('some name');

Why should I use angular-service-loader?

Because it works with the document reference and retrieves globally-accessible services, it can be quickly loaded from the browser console without having to identify a particular element context. Note that because this can access any service, it works equally well for custom services as it does for stock Angular services like $http.

How do I create a data service in angular?

To create a service in Angular, you need to run the generate service command: Two new files will be created. Navigate to the data service.ts file, and make sure the content is the same as this: This data service has now been created and hard-coded data stored in the getList function.

How to install Angular 6 in Visual Studio Code?

Open Terminal windows in Visual Studio Code and type: npm install -g @angular/cli to install Angular 6 Create new folder, named services in src\app folder. Create services as below In services folder, create new TypeScript file, named math.service.ts contains math operators


Video Answer


1 Answers

To access a service in a console, it needs to be a global variable i.e. in window object of browser. There is a little trick which i use to access a service class instance in the console.

In the constructor of the console, you can do window.myService=this but typescript wont let you do that because of window definition. Instead, you can do window['myService'] = this. Using this you can access the service using myService or window.myService.

In your case it will be:

import { Injectable } from '@angular/core';
import { TranslatePipe } from 'src/app/pipes/translate/translate.pipe';
import { LoggerService } from "src/app/services/logger/logger.service";
/**
* Injects the JSON web token service in the project
*/
@Injectable({
  providedIn: 'root'
})

/**
* This service is responsible for management of the jwt token, which would be used
* for authentication/authorization purposes. The service includes methods to save, delete
* and retrieve the token
*/
export class JwtService {


  constructor(
    private translate: TranslatePipe,
    private logger: LoggerService) {
          window['myService'] = this;
   }

  /**
   * This method fetches the token from local storage and returns it.
   *
   * @method getToken
   * @return
   */
  getToken(): string {
    var token = window.localStorage['jwtToken'];
    if (token !== undefined) {
      return token;
    } else {
      this.logger.invokeConsoleMethod('error', this.translate.transform("generic[responses][error][token][001]"));
      throw new Error(this.translate.transform("generic[responses][error][token][001]"));
    }
}

You can then access your service in the console using myService or window.myService.

Also, make sure to remove this line for production as it might cause security issues.

like image 122
Nabil Shahid Avatar answered Oct 31 '22 19:10

Nabil Shahid