1

i Have component to get list car from my Rest API like this:

export class CarIndexComponent implements OnInit, AfterViewInit {
    apiUrl: string = environment.apiUrl + '/api/v1/cars-data';

    constructor( private _script: ScriptLoaderService ) {}

    ngOnInit() {}

    ngAfterViewInit() {
        this._script.loadScripts( 'car-index', [
            'assets/app/js/pages/cars/data-ajax.js'
        ] );
    }
}

I call datatable ajax from script 'assets/app/js/pages/cars/data-ajax.js'

but inside the script i don't know how to call my apiUrl variable

method: 'GET',
url: apiUrl + '/api/v1/cars-data',
headers: {
  'authorization' : 'Bearer ' + user.token
}

the apiUrl show undefined.

3
  • Have you imported the environment.ts file in your CarIndexComponent? like this: import { environment } from './../environments/environment'; Commented Jul 17, 2018 at 9:01
  • @kboul yes i already have Commented Jul 17, 2018 at 9:17
  • Why you do not import the apiUrl in data-ajax.js file the same way as you did in the CarIndexComponent? Usually .js files are not placed inside assets folder where images or mock data are placed there. Commented Jul 17, 2018 at 9:20

1 Answer 1

2

I'm not sure why you have an external script that you need to use that way, but what you can do is add the api URL to a global variable, which your script can access

export class CarIndexComponent implements OnInit, AfterViewInit {
 //  apiUrl: string = environment.apiUrl + '/api/v1/cars-data';

    constructor( private _script: ScriptLoaderService ) 
    {
        window['apiUrl'] = environment.apiUrl + '/api/v1/cars-data';
    }

And in your script

method: 'GET',
url: window.apiUrl + '/api/v1/cars-data',
Sign up to request clarification or add additional context in comments.

3 Comments

i have external script to call datatable ajax function, if i create a helper (.ts file) and call Datatable there, i got error Property 'Datatable' does not exist on type 'JQuery<HTMLElement>'.
Glad to hear it. But I think it's be better if you could get Datatables to work properly.
yes, i'm new on Angluar, i will learn how to use Datatables properly. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.