In Angular 8, how do I access an injected service from the browser console?

故事扮演 提交于 2019-12-05 07:24:08

The injected service will be available as a property on the componentInstance. If AbcService is injected into AppComponent

  export class AppComponent {  
    constructor(private abcService: AbcService) {}
  }

then you can get it in the console with:

ng.probe(document.querySelector('app-root')).componentInstance.abcService

injector get method token value can be class reference (object) ,string or number value this related how you set the provider

providers : [
  AbcService // class ref
]

you can get the service like this

ng.probe(document.querySelector('app-root')).injector.get(AbcService)

but when you run the app you will not be able to get a refrence to AbcService from the developer console ,the AbcService is not avilable in global scope.

in case the token is just a string value

providers : [
  {provide : 'AbcService' , useClass :AbcService} , 
]

this will work

ng.probe(document.querySelector('app-root')).injector.get(`AbcService`)

in both cases if the token does not exist an error will throw

Updated!! 🚀🚀

you can save a ref to NgModuleRef class like this

platformBrowserDynamic()
  .bootstrapModule(AppModule).then(ref => {
    window['ngRef'] = ref; // 👈
  })
  .catch(err => console.error(err));

then can just create an object contains a reference to all service you want to test

import {AbcService} from './abc.service';
import {ZService} from './z.service';

export const ServRef = {
  AbcService,
  ZService
}

save this object globally

window['servRef'] = ServRef;

in the developer console you can do this

ngRef.get(servRef.AbcService);
ngRef.get(servRef.ZService)

demo ⚡⚡

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!