Angular - How can I mock an HTTP request? - javascript

I have a simple code which invokes a real HTTP request :
#Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{person?.id}}</h2>
</div>
`,
})
export class App {
name:string;
constructor(public http: Http) {
this.http.get('https://jsonplaceholder.typicode.com/posts/1')
.map(res => res.json()).subscribe(res => {
this.person = res;
},()=>{},()=>console.log('complete'));
}
}
But now I want to mock the request so that it will fetch data from a file containing :
export arrFakeData:any = {id:1};
I don't want to use a service . I want to mock the request.
Some examples shows to use XHRBackend and some shows how to extend the HTTP class, but they doesn't say how can I force the data to retrieve
I know that I should use
providers:[ /*{ provide: XHRBackend, useClass: MockBackend }*/]
But I don't know how.
Question:
How can I mock http request and return (for GET) the array from arrFakeData ?
PLUNKER

Personally, I would replace the this.http.get method call with an Observable.of so that you can continue programming against the same interface (Observable) without impacting the development of your components.
However, if you really want to do this then you will have to create a service that attaches a listener to all the incoming requests and returns an appropriate mock response using the tools provided by the #angular/http/testing module.
The service will look something as such:
import {Injectable} from "#angular/core";
import {MockBackend, MockConnection} from "#angular/http/testing";
import {arrFakeData} from "./fakeData";
import {ResponseOptions, Response} from "#angular/http";
#Injectable()
export class MockBackendService {
constructor(
private backend: MockBackend
) {}
start(): void {
this.backend.connections.subscribe((c: MockConnection) => {
const URL = "https://jsonplaceholder.typicode.com/posts/1";
if (c.request.url === URL) { // You can also check the method
c.mockRespond(new Response(new ResponseOptions({
body: JSON.stringify(arrFakeData)
})));
}
});
}
}
Once you have done this, you need to register all the services and make sure that the Http module is using the MockBackend instead of the XHRBackend.
#NgModule({
imports: [BrowserModule, HttpModule,],
declarations: [App],
providers: [
MockBackend,
MockBackendService,
BaseRequestOptions,
{
provide: Http,
deps: [MockBackend, BaseRequestOptions],
useFactory: (backend: MockBackend, options: BaseRequestOptions) => {
return new Http(backend, options);
}
}
],
bootstrap: [App]
})
export class AppModule {
}
Last but not least, you have to actually invoke the start method, which will make sure that you will actually receive the mock data from the MockBackend. In your AppComponent you can do the following.
constructor(public http: Http, public mockBackendService: MockBackendService) {
this.mockBackendService.start();
this.http.get('https://jsonplaceholder.typicode.com/posts/1')
.map(res => res.json())
.subscribe(res => {
this.person = res;
});
}
I hope this helps! See the plunker for the full example. https://plnkr.co/edit/h111to5PxbI97FIyKGJZ?p=preview

You can just make the http endpoint a JSON file containing whatever data you need. This is exactly how we did it on my last project for Google, and how I do it in my own side projects. We didn't bother mocking up http services and so on, we just pointed at a json file and left everything else the same.

Related

Mock service return undefined with nested services

I'm currently working on an Angular project and I am creating unit testing for a component using Karma + Jasmine, so I have HTML that has a ngIf calling the API Service as:
HTML
<div class="row" *ngIf="apiService.utilsService.userBelongsTo('operations')"></div">
The service in the *ngIf is the service that I want to mock on the spec.ts below
TS
export class CashFlowSalariesComponent implements OnInit, OnChanges {
constructor(
public apiService: ApiService,
) {}
SPECT.TS
describe('CashFlowSalariesComponent', () => {
let fixture: ComponentFixture < CashFlowSalariesComponent > ;
let mockApiService;
let data;
beforeEach(async(() => {
data = [{
id: 1006,
role: "Developer",
...
}]
mockApiService = jasmine.createSpyObj(['userBelongsTo'])
TestBed.configureTestingModule({
schemas: [CUSTOM_ELEMENTS_SCHEMA],
imports: [
RouterTestingModule,
FormsModule,
ReactiveFormsModule,
BrowserModule,
HttpClientTestingModule,
ToastrModule.forRoot({
positionClass: 'toast-bottom-right'
})
],
declarations: [
CashFlowSalariesComponent,
],
providers: [{
provide: ApiService,
useValue: mockApiService
}, UserService, ProfileService, VettingStatusService, ApplicationRoleService,
SeniorityLevelService, PlacementStatusService, EducationLevelService, UtilsService, ShirtSizeService,
CountryService, CityService, PostalCodeService, StateService, ClientSectorService, JobService, ProfileActivityService, ProfileSalaryActivityService, ClientService, RequestTimeOffService, TimeOffTypeService, PulsecheckDetailService, PulsecheckMasterService,
PulsecheckQuestionService, ExpenseService, DepartmentService, ExchangeRateService, SkillCategoriesService, ProfileRoleService,
ToastrService
]
})
fixture = TestBed.createComponent(CashFlowSalariesComponent);
}));
it('should set salaries data correctly', () => {
mockApiService.userBelongsTo.and.returnValue(of('operations'))
debugger;
fixture.detectChanges();
})
As you see, I tried to create mock of api service as: mockApiService = jasmine.createSpyObj(['userBelongsTo']), then use in the it as: mockApiService.userBelongsTo.and.returnValue(of('operations')), but when I debug it throws as unknown as the following picture
and the test return the following error:
Cannot read properties of undefined (reading 'userBelongsTo')
I do not know if this happen because userBelongs to it is inside another service inside apiService:
ApiService
#Injectable()
export class ApiService {
public utilsService: UtilsService;
constructor(private injector: Injector) {
this.utilsService = injector.get(UtilsService);
}
}
Utils.Service:
userBelongsTo(groupName: string) {
return this.groups.split(',').reduce((c, g) => c || g.toUpperCase() == groupName.toUpperCase(), false);
}
How can I make this work? Regards
Dependency injections should be private, why does the template HTML needs to handle the service call? Instead of delegating the service call to the template, make a proper function in the component, as a result, your template will be cleaner
<div class="row" *ngIf="getBelongsTo()"></div">
constructor(private apiService: ApiService) {}
getBelongsTo(): boolean {
// I guess userBelongsTo returns either a string or undefined,
// so using !! creates a valid boolean
// if userBelongsTo returns a valid string, returns TRUE
// if returns undefined/null returns FALSE
return !!this.apiService.utilsService.userBelongsTo('operations');
}
For testing, you need to provide the mock/fake value from userBelongsTo before starting to test. Additionally, the way you are mocking the service is wrong, it could be like the following:
const mockApiService = jasmine.createSpyObj<ApiService>('ApiService', ['userBelongsTo']);
let data;
beforeEach(() => {
data = [{ id: 1006, role: "Developer", ...}];
mockApiService.userBelongsTo.and.returnValue(of('operations'));
}
beforeEach(async() => {
TestBed.configureTestingModule({
declarations: [...],
provides: [{provide: ApiService, useValue: mockApiService}]
})
})
I do not know if this happen because userBelongs to it is inside another service inside apiService
When unit testing, you don't care how any dependecy is implemented when is injected in the component, you are mocking all dependencies so it doesn't matter.
One thing to notice, since you provided how ApiService is implemented, keep in mind that somewhere, in some module, ApiService needs to be added in the providers array since it isn't provided as root, e.x: #Injectable({ provideIn: 'root' })

Sending File inside object from angular2 to Spring Rest

Hi This question is not new but I could not find any proper way of doing this.Please help me.
Requirement
Sending a uploaded File inside the json object and handle at rest service.
Example of Sample json:
{
id:"123",
name:"XYZ",
nonProfit:[{
name:"profile1",
attachedFile: object of file
}, {
name:"profile2",
attachedFile: object of file2
}]
}
Problem:
I am able to get the file object inside json but I am not able to send to the service as I guess payload is not going right to the web service.
Is there any way that I can send the json like below and handle in the backend service.
first you have to get base64 of your file
public readFile(fileToRead: File): Observable<MSBaseReader>{
let base64Observable = new ReplaySubject<MSBaseReader>(1);
let fileReader = new FileReader();
fileReader.onload = event => {
base64Observable.next(fileReader.result);
};
fileReader.readAsDataURL(fileToRead);
return base64Observable;
}
after read base64 you should pass it to json file
let params = {
id:"123",
name:"XYZ",
nonProfit:[{
name:"profile1",
attachedFile: this.fileBase64
}
after that you can create a service to send data to backend.first of this create a server.service.ts file for call api
import {Injectable} from '#angular/core';
import {Headers, Http, RequestOptions} from '#angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/forkJoin';
import 'rxjs/add/operator/toPromise';
import {AuthenticationService} from "./authentication.service";
import {isUndefined} from "util";
#Injectable()
export class ServerService {
constructor(private http: Http) {
}
servicePost(service: string, parameters: string) {
return this.http.post('/service/' + service, parameters)
}
}
add your service to providers of module
#NgModule({
declarations: [...],
imports: [...],
providers: [AuthGuard,
ServerService],
entryComponents: [...],
bootstrap: [AppComponent]
})
export class AppModule {
}
now add your service to your constructor
constructor(private serverService: ServerService) {
}
and call your service in component.
this.service.servicePost('subDirectoryOfService',params).subscribe(data=>{dosomething after call api})
now in backend you will got in this service with path:/service/subDirectoryOfService
in controller you got in this method
#RequestMapping('/service/subDirectoryOfService')
public String subDirectoyOfService(#FormParam String params){
JSONObject json = new JSONObject(params);
String base64 = json.getString("attachedFile");
System.out.println("base64 of file: "+ base64);
return "{\"res\":\"success\"}"
}

Angular 5 Unit Testing cannot read property 'http' of undefined

I am attempting to write a helper function in an Angular test leveraging HttpTestingController. The reason being is because I will eventually have a series of endpoints within my Angular service, RequestService, that I want to test within this testing file. I do not want to repeatedly inject my RequestService and HttpTestingController instances into each test function that tests the service. That is redundant. Rather, I would prefer to have a single test function that takes the injected RequestService and HttpTestingController instances and repeatedly passes them into the helper function I have created, requestHelper. This way when I want to test additional endpoints, all I need to do is make a call to the helper function and provide the parameters that are needed.
The problem I am bumping into is that when the helper function runs, the service's instance for some reason does not appear to exist, Even though the test is able to access the service's functions. When it reaches my service method's call to the http.get within the callEndpoint function, it gives me the below error:
Failed: Cannot read property 'http' of undefined
This does not make sense to me because the this keyword is referring to the instance of the Angular service, and the test case is able to reach the service's function, so how could this possibly be undefined?
Here is my test spec:
import { TestBed, async, inject } from '#angular/core/testing';
import { HttpClientModule, HttpRequest, HttpParams } from '#angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '#angular/common/http/testing';
import { RequestService } from './request.service';
describe(`RequestService`, () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
HttpClientModule,
HttpClientTestingModule
],
providers: [
RequestService
]
});
}));
afterEach(async(inject([HttpTestingController], (backend: HttpTestingController) => {
backend.verify();
})));
it(`TESTING INJECTION`, async(inject([RequestService, HttpTestingController],
(service: RequestService, backend: HttpTestingController) => {
requestHelper(service.callEndpoint,'https://endpointurl.com',backend);
})));
function requestHelper(serviceCall: Function, url: string, backendInstance: any) {
serviceCall(...serviceParams).subscribe();
backendInstance.expectOne((req: HttpRequest<any>) => {
return req.url === url
&& req.method === 'GET';
}, 'GET');
}
});
And the respective service that the spec is testing
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { RequestOptions } from '#angular/http';
import { Observable } from 'rxjs/Observable';
#Injectable()
export class RequestService {
private requestOptions = {
headers: new HttpHeaders({'Locale': 'en_US'})
};
constructor(private http: HttpClient) { }
callEndpoint(state: string, countryCode: string): Observable<Object> {
return this.http.get(`https://endpointurl.com`,this.requestOptions);
}
}
Thank you for your help!
You can bind the context in the it block:
it(`TESTING INJECTION`, async(inject([RequestService, HttpTestingController],
(service: RequestService, backend: HttpTestingController) => {
requestHelper(service.callEndpoint.bind(service),'https://endpointurl.com',backend);
})));

Can't bind JSON results to Component variable

I'm trying a simple component that has to pull data from a JSON file. I'm almost copying the functionality from generated Fountain App, but for some reason I can't get the desired results. I have a component like:
import {Component, Inject} from "#angular/core";
import {Http} from '#angular/http';
#Component({
selector: 'body-selector',
template: require('./body.html')
})
#Inject(Http)
export class BodyComponent {
constructor(http: Http) {
this.http = http;
this.getText('app/texts/main.json').subscribe(result => {
console.log(result);
this.texts = result;
});
console.log(this.texts);
}
getText(url) {
return this.http.get(url).map(response => response.json());
}
}
on the first console.log I have [Object object] [Object object] [Object object], which is correct as I have three entries in the JSON. On the second however I've got undefined, which turns into an error in the browser.
Error in ./BodyComponent class BodyComponent - inline template:3:6 caused by: Cannot read property 'title' of undefined
I'm looking at the example generated from the fountain app, but I can't get what I'm doing wrong.
You have multiple problems:
The first console.log is inside the callback, where this.texts has just been set. However the second one is outside the callback, so it won't have been. Therefore you'll always see undefined for that, because...
...you never set a default value for this.texts, and your template apparently doesn't have any e.g. *ngIf to handle it being null or undefined, causing errors prior to the callback being called.
Below is your code, refactored to start with an empty this.texts (assuming it should be an array; please adapt to taste) and simplifying the injection of Http. Also note the comments, and that I've used templateUrl to avoid the require and OnInit to trigger the HTTP call slightly later in the component lifecycle rather than doing it in the constructor.
import {Component, OnInit} from '#angular/core'; // note consistent quotes
import {Http} from '#angular/http';
#Component({
selector: 'body-selector',
templateUrl: './body.html',
})
export class BodyComponent implements OnInit {
texts: any[] = []; // start with an empty array
constructor(private http: Http) { } // inject Http here, no need to assign to this
ngOnInit() {
this.http
.get('app/texts/main.json')
.map(response => response.json())
.subscribe(result => {
console.log(result); // only log *inside* the callback
this.texts = result;
});
// outside the callback, the HTTP call hasn't yet finished
}
}
You could also solve this by having an ngIf in your HTML to prevent the element from being loaded before the data is.
<div class="main-container" *ngIf="texts">
...
</div>
I'd strongly recommend running through the basic Angular 2 tutorials to get on top of this stuff, see e.g. the Tour of Heroes.
You get undefined because this:
this.getText('app/texts/main.json')
Is an asynchronous call that gets the data and when it's done, it executes the code in the 'subscribe' block. So this.text is empty until that executes. That is the expected behavior.
Better way to use data or making API call use service:
import { Injectable } from '#angular/core';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
#Injectable()
export class BodyService {
private _requestOptions: RequestOptions;
private static handleError(error: Response): ErrorObservable {
return Observable.throw(error.json().error || 'Server error');
}
constructor(private http: Http) {
const headers = new Headers({ 'Accept': 'application/json' });
this._requestOptions = new RequestOptions({ headers: headers});
}
/**
* [getJsonData will get data of json file: main.json ]
*/
getJsonData() {
return this.http.get('app/texts/main.json', this._requestOptions)
.map(res => res.json()) //needs to add map for converting data in json format
.catch(BodyService.handleError);
}
}
Now Inject this service in your component:
import {Component, OnInit} from '#angular/core';
import { BodyService } from './adminModules.service';
#Component({
selector: 'body-selector',
templateUrl: './body.html',
providers: [BodyService]
})
export class BodyComponent implements OnInit {
texts: any = []; // start with an empty array
errorMessage: any;
constructor(private _bodyService: BodyService) {}
ngOnInit() {
this._bodyService.getJsonData()
.subscribe(data => {
this.texts = data;
console.log('data', this.texts);
}, error => {
this.errorMessage = <any> error;
})
}
}
For calling service, you can call directly in constructor or create one method and call either in constructor or any place where you want to call.
Hope it will helpful for you :)

Angular 2 - HTTP request resolver before module's bootstrap [duplicate]

Is there a way to pass arguments rendered on the backend to angular2 bootstrap method? I want to set http header for all requests using BaseRequestOptions with value provided from the backend. My main.ts file looks like this:
import { bootstrap } from '#angular/platform-browser-dynamic';
import { AppComponent } from "./app.component.ts";
bootstrap(AppComponent);
I found how to pass this arguments to root component (https://stackoverflow.com/a/35553650/3455681), but i need it when I'm fireing bootstrap method... Any ideas?
edit:
webpack.config.js content:
module.exports = {
entry: {
app: "./Scripts/app/main.ts"
},
output: {
filename: "./Scripts/build/[name].js"
},
resolve: {
extensions: ["", ".ts", ".js"]
},
module: {
loaders: [
{
test: /\.ts$/,
loader: 'ts-loader'
}
]
}
};
update2
Plunker example
update AoT
To work with AoT the factory closure needs to be moved out
function loadContext(context: ContextService) {
return () => context.load();
}
#NgModule({
...
providers: [ ..., ContextService, { provide: APP_INITIALIZER, useFactory: loadContext, deps: [ContextService], multi: true } ],
See also https://github.com/angular/angular/issues/11262
update an RC.6 and 2.0.0 final example
function configServiceFactory (config: ConfigService) {
return () => config.load();
}
#NgModule({
declarations: [AppComponent],
imports: [BrowserModule,
routes,
FormsModule,
HttpModule],
providers: [AuthService,
Title,
appRoutingProviders,
ConfigService,
{ provide: APP_INITIALIZER,
useFactory: configServiceFactory
deps: [ConfigService],
multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }
If there is no need to wait for the initialization to complete, the constructor of `class AppModule {} can also be used:
class AppModule {
constructor(/*inject required dependencies */) {...}
}
hint (cyclic dependency)
For example injecting the router can cause cyclic dependencies.
To work around, inject the Injector and get the dependency by
this.myDep = injector.get(MyDependency);
instead of injecting MyDependency directly like:
#Injectable()
export class ConfigService {
private router:Router;
constructor(/*private router:Router*/ injector:Injector) {
setTimeout(() => this.router = injector.get(Router));
}
}
update
This should work the same in RC.5 but instead add the provider to providers: [...] of the root module instead of bootstrap(...)
(not tested myself yet).
update
An interesting approach to do it entirely inside Angular is explained here https://github.com/angular/angular/issues/9047#issuecomment-224075188
You can use APP_INITIALIZER which will execute a function when the
app is initialized and delay what it provides if the function returns
a promise. This means the app can be initializing without quite so
much latency and you can also use the existing services and framework
features.
As an example, suppose you have a multi-tenanted solution where the
site info relies on the domain name it's being served from. This can
be [name].letterpress.com or a custom domain which is matched on the
full hostname. We can hide the fact that this is behind a promise by
using APP_INITIALIZER.
In bootstrap:
{provide: APP_INITIALIZER, useFactory: (sites:SitesService) => () => sites.load(), deps:[SitesService, HTTP_PROVIDERS], multi: true}),
sites.service.ts:
#Injectable()
export class SitesService {
public current:Site;
constructor(private http:Http, private config:Config) { }
load():Promise<Site> {
var url:string;
var pos = location.hostname.lastIndexOf(this.config.rootDomain);
var url = (pos === -1)
? this.config.apiEndpoint + '/sites?host=' + location.hostname
: this.config.apiEndpoint + '/sites/' + location.hostname.substr(0, pos);
var promise = this.http.get(url).map(res => res.json()).toPromise();
promise.then(site => this.current = site);
return promise;
}
NOTE: config is just a custom config class. rootDomain would be
'.letterpress.com' for this example and would allow things like
aptaincodeman.letterpress.com.
Any components and other services can now have Site injected into
them and use the .current property which will be a concrete
populated object with no need to wait on any promise within the app.
This approach seemed to cut the startup latency which was otherwise
quite noticeable if you were waiting for the large Angular bundle to
load and then another http request before the bootstrap even began.
original
You can pass it using Angulars dependency injection:
var headers = ... // get the headers from the server
bootstrap(AppComponent, [{provide: 'headers', useValue: headers})]);
class SomeComponentOrService {
constructor(#Inject('headers') private headers) {}
}
or provide prepared BaseRequestOptions directly like
class MyRequestOptions extends BaseRequestOptions {
constructor (private headers) {
super();
}
}
var values = ... // get the headers from the server
var headers = new MyRequestOptions(values);
bootstrap(AppComponent, [{provide: BaseRequestOptions, useValue: headers})]);
In Angular2 final release, the APP_INITIALIZER provider can be used to achieve what you want.
I wrote a Gist with a complete example: https://gist.github.com/fernandohu/122e88c3bcd210bbe41c608c36306db9
The gist example is reading from JSON files but can be easily changed to read from a REST endpoint.
What you need, is basically:
a) Set up APP_INITIALIZER in your existent module file:
import { APP_INITIALIZER } from '#angular/core';
import { BackendRequestClass } from './backend.request';
import { HttpModule } from '#angular/http';
...
#NgModule({
imports: [
...
HttpModule
],
...
providers: [
...
...
BackendRequestClass,
{ provide: APP_INITIALIZER, useFactory: (config: BackendRequestClass) => () => config.load(), deps: [BackendRequestClass], multi: true }
],
...
});
These lines will call the load() method from BackendRequestClass class before your application is started.
Make sure you set "HttpModule" in "imports" section if you want to make http calls to the backend using angular2 built in library.
b) Create a class and name the file "backend.request.ts":
import { Inject, Injectable } from '#angular/core';
import { Http } from '#angular/http';
import { Observable } from 'rxjs/Rx';
#Injectable()
export class BackendRequestClass {
private result: Object = null;
constructor(private http: Http) {
}
public getResult() {
return this.result;
}
public load() {
return new Promise((resolve, reject) => {
this.http.get('http://address/of/your/backend/endpoint').map( res => res.json() ).catch((error: any):any => {
reject(false);
return Observable.throw(error.json().error || 'Server error');
}).subscribe( (callResult) => {
this.result = callResult;
resolve(true);
});
});
}
}
c) To read the contents of the backend call, you just need to inject the BackendRequestClass into any class of you choice and call getResult(). Example:
import { BackendRequestClass } from './backend.request';
export class AnyClass {
constructor(private backendRequest: BackendRequestClass) {
// note that BackendRequestClass is injected into a private property of AnyClass
}
anyMethod() {
this.backendRequest.getResult(); // This should return the data you want
}
}
Let me know if this solves your problem.
Instead of having your entry point calling bootstrap itself, you could create and export a function that does the work:
export function doBootstrap(data: any) {
platformBrowserDynamic([{provide: Params, useValue: new Params(data)}])
.bootstrapModule(AppModule)
.catch(err => console.error(err));
}
You could also place this function on the global object, depending on your setup (webpack/SystemJS). It also is AOT-compatible.
This has the added benefit to delay the bootstrap, whenit makes sense. For instance, when you retrieve this user data as an AJAX call after the user fills out a form. Just call the exported bootstrap function with this data.
The only way to do that is to provide these values when defining your providers:
bootstrap(AppComponent, [
provide(RequestOptions, { useFactory: () => {
return new CustomRequestOptions(/* parameters here */);
});
]);
Then you can use these parameters in your CustomRequestOptions class:
export class AppRequestOptions extends BaseRequestOptions {
constructor(parameters) {
this.parameters = parameters;
}
}
If you get these parameters from an AJAX request, you need to bootstrap asynchronously this way:
var appProviders = [ HTTP_PROVIDERS ]
var app = platform(BROWSER_PROVIDERS)
.application([BROWSER_APP_PROVIDERS, appProviders]);
var http = app.injector.get(Http);
http.get('http://.../some path').flatMap((parameters) => {
return app.bootstrap(appComponentType, [
provide(RequestOptions, { useFactory: () => {
return new CustomRequestOptions(/* parameters here */);
}})
]);
}).toPromise();
See this question:
angular2 bootstrap with data from ajax call(s)
Edit
Since you have your data in the HTML you could use the following.
You can import a function and call it with parameters.
Here is a sample of the main module that bootstraps your application:
import {bootstrap} from '...';
import {provide} from '...';
import {AppComponent} from '...';
export function main(params) {
bootstrap(AppComponent, [
provide(RequestOptions, { useFactory: () => {
return new CustomRequestOptions(params);
});
]);
}
Then you can import it from your HTML main page like this:
<script>
var params = {"token": "#User.Token", "xxx": "#User.Yyy"};
System.import('app/main').then((module) => {
module.main(params);
});
</script>
See this question: Pass Constant Values to Angular from _layout.cshtml.

Categories

Resources