I am having trouble accessing my JSON data via HTTP get request in Angular 2 when using TypeScript

I am working on developing a JSON file configuration that can be accessed via HTTP GET request in order to retrieve the desired value from the config file and pass it to another component. However, whenever I try to return the value, it shows up as undefined.

My Config.json

[ {"urlServer": "http://localhost:56877"}]

My Config.Service

In my configService class:


export class configService
{
    url: string;

    constructor(public _http: Http)
    {
        let injector = Injector.resolveAndCreate([loggerService]);
        let logger = injector.get(loggerService);

        try {
            return this._http.get('/app/config.json',
            {
                headers: contentHeaders
            })
            .map((res: any) =>
            {
                let data = <configModel>res.json();
                this.url = data.urlServer;
                JSON.stringify(this.url);
            });
        }
        catch (ex) {
            logger.registarErros('configService', ex);
        }
    }

    returnConfig()
    {
        return this.url;
    }
}

Now in my other Component:


constructor(public _http: Http, public config: configService)
{
    this.token = sessionStorage.getItem('token');
    this.username = sessionStorage.getItem('username');
}

login(username: String, password: String)
{
    let injector = Injector.resolveAndCreate([loggerService]);
    let logger = injector.get(loggerService);

    try
    {
        alert(this.config.url);
        return this._http.post('http://localhost:56877/api/Login/EfectuaLogin', JSON.stringify({ username, password }),
        {
            headers: contentHeaders
        })
        .map((res: any) => 
        {
            let data = <authLoginModel>res.json();
            this.token = data.token;
            this.username = data.nome;
            sessionStorage.setItem('token', this.token);
            sessionStorage.setItem('username', this.username);
            return Observable.of('authObservable');
        });
    }
    catch (ex) {
        logger.registarErros('authentication', ex);  
    }

}

I am facing difficulty in resolving this issue and would greatly appreciate your help as I am relatively new to Angular 2 development. Thank you for your assistance.

Answer №1

The issue at hand arises from the asynchronous loading of the configuration. One way to address this is by utilizing the flatMap operator:

@Injectable()
export class ConfigService {
  urlServer:string;

  constructor(public _http: Http) {
  }

  getConfig() {
    if (this.urlServer) {
      return Observable.of(this.urlServer);
    }

    return this._http.get('/app/config.json', {
      headers: contentHeaders
    })
    .map((res: any) => {
      let data = <configModel>res.json();
      return data.urlServer;
    }).do(urlServer => {
      this.urlServer = urlServer;
    });
  }
}

In your component, you can implement it like so:

login(username: String, password: String) {
  return this.configService.getConfig().flatMap(urlServer => {
    this._http.post('http://localhost:56877/api/Login/EfectuaLogin',  
      JSON.stringify({ username, password }),
      {
        headers: contentHeaders
      })
      .map((res: any) => 
      {
        let data = <authLoginModel>res.json();
        this.token = data.token;
        this.username = data.nome;
        sessionStorage.setItem('token', this.token);
        sessionStorage.setItem('username', this.username);
        return data; // or another value
      });
    }
  });
}

An alternative approach involves bootstrapping asynchronously after acquiring the configuration:

var app = platform(BROWSER_PROVIDERS)
   .application([BROWSER_APP_PROVIDERS, appProviders]);

service.getConfig().flatMap((url) => {
  var configProvider = new Provider('urlServer', { useValue: urlServer});
  return app.bootstrap(appComponentType, [ configProvider ]);
}).toPromise();

For more on this second approach, refer to this question:

  • angular2 bootstrap with data from ajax call(s)

You could enhance the above approach by incorporating a CustomRequestOptions:

import {BaseRequestOptions, RequestOptions, RequestOptionsArgs} from 'angular2/http';

export class CustomRequestOptions extends BaseRequestOptions {
  merge(options?:RequestOptionsArgs):RequestOptions {
    options.url = 'http://10.7.18.21:8080/api' + options.url;
    return super.merge(options);
  }
}

More insights on this can be found in this question:

  • Angular 2 - global variable for all components

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide on passing an ngFor object variable to a function

I am trying to display subcategories for each category in my *ngFor list. The subcategory data is retrieved from Firebase using the category_id, but I am struggling to pass the category_id from the HTML to the function for every member of the category. ho ...

Exploring composite search conditions in MongoDB with JavaScript

Being a newcomer to Node JS and mongo DB, I am currently working on a project that involves fetching data from mongo db using a JavaScript file. The challenge I am facing is to search multiple columns in order to retrieve the desired results. Initially, w ...

What are the specific purposes of utilizing semantic versioning (semver) notation within the package.json file?

Could someone clarify the specific distinctions between the semver notations found in package.json file? I'd appreciate a detailed explanation. ...

Converting Typescript fat arrow syntax to regular Javascript syntax

I recently started learning typescript and I'm having trouble understanding the => arrow function. Could someone clarify the meaning of this JavaScript code snippet for me: this.dropDownFilter = values => values.filter(option => option.value ...

Issues encountered with the `npm install` command in Azure build pipelines for a simple Angular application

Transferred the GitHub Repository mentioned in this link to Azure Repository. Established the Build Pipeline using Classic Editor, and you can find the YAML Code below: trigger: branches: include: - refs/heads/master jobs: - job: Job_1 display ...

How can I convert an xlsx file to JSON using ExcelJS in Node.js?

https://github.com/guyonroche/exceljs I am a beginner with exceljs and just came across the description of exceljs on github. The description states: "Read, manipulate and write spreadsheet data and styles to XLSX and JSON." I am looking for a way to ...

Looking up a destination with the Google Places API

My dilemma lies in dealing with an array of place names such as 'Hazrat Nizamuddin Railway Station, New Delhi, Delhi, India' and similar variations. These variations serve as alternative names for the same location, adding complexity to my task. ...

What issues arise from using ng-content within a web component?

I have a unique component structure for my website: <div (click)="popup.showAsComponent()"> <ng-content></ng-content> </div> Here is how I implement it: <my-web-component><button>Click!</button></my ...

Using Facebook login with Node.js: A comprehensive guide

Working on a web application with Angular on the frontend and Node.js on the backend. The frontend includes a Facebook login button (js-sdk) to fetch user data via the Graph API. The backend consists of rest APIs that require authentication. I attempted t ...

"An issue has been identified where the ui.bootstrap.accordion component is not functioning correctly

I struggled to implement the accordion feature from https://angular-ui.github.io/bootstrap/#!#accordion. After countless attempts with bootstrap version 4.0.0, I switched to 3.0.0 and finally achieved the desired results. Version 4 displayed only a clickab ...

Exploring the Angular RouterModule within a Java WAR Deployment

In my Angular 6.0.5 application, I leverage Angular's Routing feature to define paths like: http://localhost:8080/area http://localhost:8080/barn http://localhost:8080/tower During development, running the app with ng serve allows me to directly en ...

How can I use a string variable in Angular 2 to create a dynamic template URL

@Component({ selector: 'bancaComponent', templateUrl: '{{str}}' }) export class BancaComponent implements OnInit { str: String; constructor(private http: Http) { } ngOnInit(): void { this.str = "./file.component.html"; } An ...

Learn how to retrieve data outside of the .subscribe function in an Angular 2 polling service

// I'm facing an issue where I am unable to assign values from outside the subscribe function to any variable. In my current project, I am fetching JSON content using the http.post() method and storing it in a variable. However, I need to access this ...

obtaining the value of an input using typescript (put request)

Does anyone know how to extract input values and store them as JSON? I'm having trouble with accessing the input value in this scenario. When I attempt document.querySelector("todo-text").value, it results in an error. const NewTodo: React.FC<NewT ...

The JSON encoding done by Dart's json.encode is not meeting the requirements of Firebase Function

I've been grappling with a persistent issue for some time now, and I can't seem to pinpoint the exact cause. In my Dart(2) code, the json.encode() function is not producing the desired output. The input being passed is a Map<String, dynamic&g ...

Rearranging lists in JHipster: What is the best way to do it?

Seeking advice and guidance on implementing a drag-and-drop reorderable list in JHipster 6.7.1. To illustrate, picture creating a custom ordered list of objects where users can add, remove, and rearrange items. For instance, wanting to move [Epsilon] betw ...

Transform the JSON data into a Map containing key-value pairs of type String

I have a JSON input that looks like this: {"a": "x", "b": "y", "c": "z", .... } My goal is to convert this JSON into a Map of type Map[String, String] This map should consist of key-value pairs. Is there a way to achieve this using circe? Keep in mind ...

Having trouble getting web components registered when testing Lit Element (lit-element) with @web/test-runner and @open-wc/testing-helpers?

Currently, I am working with Lit Element and Typescript for my project. Here are the dependencies for my tests: "@esm-bundle/chai": "^4.3.4-fix.0", "@open-wc/chai-dom-equals": "^0.12.36", "@open-wc/testing-help ...

Utilizing Restangular to capture and manipulate error messages

I'm currently working on implementing an interceptor for all requests. I have decided to utilize [addResponseInterceptor][1] in restangular. The documentation states: The responseInterceptor is called after each response is received from the serve ...

What is the best way to transform a JSON Array into a List<>?

I am trying to extract the values from each object within the attendance array in my JSON data: {"name":" ","course":"","attendance":[{"name":"INTERNATIONAL FINANCE","type":"Theory","conducted":"55","present":"50"},{"name":"INDIAN CONSTITUTION","type":"Th ...