Tips for displaying an Angular 2 HTML page once the REST webservice response is received

When I retrieve a REST web service response, I can easily display it on the screen without any issues. However, the problem arises when the initial value of the web service call result is visible on the page. What steps should I take to render the page only after receiving a response from the web service? As of now, I am able to see the initial values of userInfo and userName. Below is a snippet of the code.

Regards, Alper


export class NavigationComponent implements OnInit {
  response:any;
  errorMessage:any;
  form:FormGroup;
  obj = {"one": "", "two": "", "three": "", "four": ""};
  webserviceUrl = "https://httpbin.org/post";
  webServiceUrlGet = "https://jsonplaceholder.typicode.com/posts/1";
  username = "alper"
  userInfo = "alper Info";
  componentName =  'AppComponent';

  ngOnInit():void {
    this.getUserName();
  }

  getUserName() {

    this.http.get(this.webServiceUrlGet)
      .subscribe(
        data => {
          this.userInfo = data.json();
          this.username = this.userInfo.userId;
        },
        error => this.errorMessage = error);
        
    return this.username;
  }
}

Answer №1

This approach may not prove successful

.subscribe(
  function (data)

It is recommended to use

.subscribe(
  (data) =>

in order for this to be functional within the callback.

If you wish to only display the template once the response has been received, a possible solution could be

<ng-container *ngIf="userInfo">
  <!-- actual template content here -->
</ng-container>

Answer №2

I concur with the recommendation to utilize fat arrows instead of traditional function syntax. Another approach could involve encapsulating 'this' within your closure in the following manner:

export class NavigationComponent implements OnInit {
    response:any;
    errorMessage:any;
    form:FormGroup;
    obj = {"one": "", "two": "", "three": "", "four": ""};
    webserviceUrl = "https://httpbin.org/post";
    webServiceUrlGet = "https://jsonplaceholder.typicode.com/posts/1";
    username = "alper"
    userInfo = "alper Info";
    componentName =  'AppComponent';

    ngOnInit():void {
        this.getUserName();
    }

    getUserName() {
        let that = this;
        this.http.get(this.webServiceUrlGet)
        .subscribe(
            (data) => {
                that.userInfo = data.json();
                that.username = that.userInfo.userId;
            },
        error => that.errorMessage = <any>error);
        return that.username; // Not essential to include a return statement
    }
}

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

Tips for integrating Angular Material styles into Sonarque

Can Sonarqube analyze my Angular application prominently using Angular Material? The styling I have is: .some-class { mat-icon { color: red; } } Since Angular Material is globally added through angular.json configuration, So ...

Incorporating a personalized component into the software

Currently, I am in the process of integrating the FormValidator Module into my application. I have created a service that I am looking to incorporate into this module. After using ng CLI to add the module and service, I understand that I need to import the ...

Create a combined string from a structure resembling a tree

In my web application, I have a type that defines the different routes available: interface IRoute { readonly path: string, readonly children?: IRoute[] } I want to create a union type containing all possible paths based on an IRoute object. Let&apos ...

Navigating route parameters in Angular Universal with Java

I am currently developing a web application using Angular 5 with Server Side Rendering utilizing Angular Universal for Java. The project repository can be found here. One of the challenges I am facing is with a parameterized route defined in Angular as /pe ...

Potentially null object in react typescript

In my React application with TypeScript, I have completed the implementation of a chart but encountered an error in the following line: backgroundColor: gradientFill ? gradientFill : chartRef.current.data.datasets[0].backgroundColor, T ...

Trouble encountered while attempting to install ng2-bootstrap within my Angular 2 project

I've been attempting to integrate ng-bootstrap into my Angular 2 application for dropdown functionality. However, I'm encountering the following error in the console: Console error Here is the snippet of my System.config.js code: System.config. ...

The Fusion of Apollo GraphQL Server and TypeScript: A Match Made

Lately, I've been immersed in a project that utilizes the node.js + express + typescript + Apollo server stack. During my research on Apollo client, I came across the TypeScript section, but surprisingly found little information regarding TypeScript f ...

Can you please explain the concept of the "Angular main directory"?

I've been following a tutorial on building a simple CRUD application using Angular and MongoDB, but I'm stuck at this step: "Inside the root folder of your Angular project, create a new directory called api and navigate into it. Keep in mind tha ...

Creating an interface for writing types in Firebase functions/storage/database

What are the TypeScript types for Firebase functions, storage, and admin? I'm fairly new to TypeScript and currently in the process of updating my JavaScript code to TypeScript. Within my code, I am generating a context object. const context = { ...

Exploring the capabilities of the Angular 2 HTTP service

I am just beginning my journey with Angular 2. Here is a service I have created: @Injectable() export class PostsService { constructor(private http: Http) { } getAllPosts() { return this.http.get('/api/posts') .map ...

There is an error in an Angular library project where the SVG component is causing an issue with an 'Unknown word'

Currently, I am developing a custom npm library package using Angular 8.1.3. When attempting to include an SVG file as a component template within the library project, the build command ng build <project-name> throws an error stating my-comp.compone ...

Outputting double columns with Typescript Sequelize associations

I am currently in the process of constructing table models using sequelize along with typescript. Here is an example of one of my models: 'use strict'; import { Model, InferAttributes, InferCreationAttributes, CreationOptional } from 'seque ...

The button alignment on Angular UI is not appearing correctly due to issues with Bootstrap

<div class="container"> <h1 class="mt-3">Category List</h1> <div class="d-flex justify-content-end-mt-3"> <a href="" class="btn btn-primary"> Add Category< ...

An issue was encountered during the prerendering of the page "/". For more information on this error, visit: https://nextjs.org/docs/messages/prerender-error Attempting to adjust the request (unable to determine

It's been four days and I'm still stuck. I've seen some suggestions to use axios and set the timeout or switch from HTTP to HTTPS when fetching data, but nothing has worked. I'm now four days behind deadline and the client is not going ...

What is causing the additional text to be displayed above the arrows in my Angular datetimepicker input field?

I'm facing an issue with the datetimepicker in my Angular project where strange lines of text are appearing over the arrows on the time input field. These lines seem to be related to incrementing/decrementing hours/mins, but I can't figure out wh ...

How to pass a single property as a prop in TypeScript when working with React

I have a main component with a parent-child relationship and I am looking for a way to pass only the product name property as props to my "Title" component. This way, I can avoid having to iterate through the information in my child component. To better i ...

Is it possible to utilize an ng template within one component and then reference its template in another HTML file?

I'm experimenting with using ng-template in a separate component and referencing it in other parts of the html. Is this possible? I've tried different approaches but seem to be missing something. Can you help me understand where I might be going ...

How to toggle code block visibility in Angular's ngOnInit() method

I'm currently analyzing different design patterns to optimize the number of REST calls when implementing a 'save while typing feature'. To provide a general overview, in my ngOnInit() function, I have included the following code snippet (wit ...

Effective Techniques for Binding Loaded Data to @ng-select Component in Angular 5

While using angular 5 and @ng-select, I encountered some challenges with binding to previously selected data (especially in edit forms). Definition of Ngselect <ng-select [items]="contenedores$ | async" bindLabel="numero" bindValue= ...

Retrieve all objects of the selected value using Angular autocomplete when an option is selected

I am currently working with an autocomplete component. I am passing an array of objects and would like to retrieve all item information (option) when an option is selected, not just the field value (option.name). <form class="example-form"> ...