Creating a dynamic Angular 2 application using Bootstrap with external data sources

How can I delay the loading of an Angular 2 application until external data is received?

For instance, if there is an external application on the same HTML page, and I need to pass some data to my app service before initialization. Let's say this data is an API URL, like 'some_host/api/', how do I ensure my application doesn't start until this information is retrieved?

Is it feasible to trigger a method in my application from the script of the external app, like so:

application.initApplication('some data string', some_object);

index.html

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>App</title>
  <base href="/">
  <link>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<script>
  application.initApplication('api/url', some_object);
</script>


  <app-root
   >Loading...</app-root>

</body>
</html>

Answer №1

If you're looking to kickstart a project, here's a helpful guide: Check out this plnkr example: https://plnkr.co/edit/b0XlctB98TLECBVm4wps

To start off, make sure to set the URL on the window object, as shown in the code snippet below. Within your root component, include *ngif="ready". The "ready" variable should be a public member of your root component that is initially set to false.

Subsequently, utilize the specified URL in your service or root component using the http service. Once the request is successfully completed, set the "ready" variable to true. Your application will then display the desired content, following the outlined steps in the app.ts file and the app component's ngOnInit method.

Here is the code excerpt:

File: src/app.ts

import { Component, NgModule, VERSION, OnInit } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule, Http } from '@angular/http';

@Component({
  selector: 'my-app',
  template: `
    <div *ngIf="ready">
      <h2>Hello {{name}}</h2>
    </div>
  `,
});

export class App implements OnInit {
  name: string;
  ready: boolean;
  constructor(private http: Http) {
    this.name = `Angular! v${VERSION.full}`
  }
  ngOnInit(){
    const self = this;
    const url = window["myUrl"];
    this.http.get(url)
    .subscribe(
      (res) =>
      {
        // do something with res
        console.log(res.json())
        self.ready = true;
      },
      (err) => console.error(err)),
      () => console.log("complete"))
  }
}

@NgModule({
  imports: [ BrowserModule, HttpModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

File: src/data.json

{
  "key1": "val1",
  "key2": "val2"
}

File: src/index.html

<header>
    ...
    <script>window['myUrl'] = 'data.json'</script>
    ...
</header>

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

Toggle between pausing and running CSS animations with this handy button!

My awesome graphic animation is in CSS and SVG format. I've been struggling to add a play/pause button to control the animation on click. Here is what I have so far: .animation1 { --animation-delay: 0.1s; animation: ani_keyframes 1 ...

Send information using jQuery AJAX

Currently, I am attempting to use AJAX to submit data to my table. Below is the form I have created for this purpose: <form> Total <input type="text" id="total" name="total" /><br /> Bill name<input type="text" id="bill-name" ...

Any suggestions on how to customize the tawk.to positioning within a Next Js script?

I've been attempting to adjust the positioning of the Tawk.to Sticky button on my Next js website using CSS, but it doesn't seem to be working. Below is the script within the Next Js script tag: <Script dangerouslySetInnerHTML={{ __html: ` ...

Tips for organizing a list in Angular 1 when a button is clicked

I'm looking for help with sorting a list in Angular 1 when a button is clicked. I want the ability to toggle between ascending and descending order on each click. Here is a link to the code: https://plnkr.co/edit/HYuk7DAgOY6baWhrvXko?p=preview var ap ...

Dealing with the process of single sign out from Identity Server4 using frontchannel

We have a unique solution that utilizes multiple Single Page Applications (SPAs) developed in both Angular and AngularJS. These applications integrate the oidc-client-js library for authentication with Identity Server 4. However, due to limitations of Angu ...

The error message "TypeError Cannot read properties of undefined (reading 'backdrop') - bootstrap v5.2.1 modal" is indicating that there is an

While working with the bootstrap modal, an error has been encountered ( TypeError Cannot read properties of undefined (reading 'backdrop') ), which has been logged in our bug tracker. However, attempts to replicate this error have been unsuccessf ...

Utilizing V-bind for dynamically generated components

I am working on a basic code that allows users to input data in fields and dynamically add more fields by clicking a button. I need to save the information entered in these additional input fields. <div id='wordslist'> <div cl ...

What is the best way to set the typing of a parent class to the child constructor?

I am seeking a method to inherit the parameter types of a parent's constructor into the child's constructor. For example: class B extends A { constructor (input) { super(input); } } I attempted the following: class B extends ...

Having trouble with the ::after element in my React component for my latest React 3D portfolio project

For my portfolio project, I am following a tutorial by LamaDev (https://www.youtube.com/watch?v=qALsVa-V9qo&t=2334s&ab_channel=LamaDev). At around timestamp 36:40, he creates a ::after selector which is not working for me, even though the rest of t ...

Tips for reusing multiple sequences of chained transitions in D3

Looking for a more efficient way to code two lengthy sequences of chained transitions with varying order, properties, and attributes. For example, one sequence might be a, b, c, d, e, f, g, h, and the other e, f, g, h, a, b, c, d. Tried the code below with ...

Inquiries for Web-Based Applications

As I contemplate coding my very first webapp, I must admit that my skills are somewhere between beginner and intermediate in html, css, js, jquery, node, sql, and mongodb. However, the challenge lies in not knowing how to bring my vision to life. My ulti ...

Are you patiently anticipating the definition of variables?

As a newcomer to JavaScript, I am experimenting with creating an API that can send requests to other websites and then display the data in an EJS template. I have written some functions to handle the requests, but I am encountering issues when trying to a ...

Issue with Vuetify password field: label overlaps with v-text-field

I'm currently working on a logging feature using Vuetify and Firebase. My goal is to hide the password input field but when I set the type as 'password' for the v-text-field, it causes 4 dots to overlap with the label of the password field a ...

Is there a way to simultaneously upload a file and incorporate JSON data using the Fetch API?

Hey there, I hope your day is going well. Currently, I am using the Fetch API to send files to a server and I also need to include a JSON string for my backend. However, I'm facing some issues in achieving this. Here is the current state of my upload ...

"Enhance your data display with PrimeNG Table components and easily customize layouts

I am currently utilizing PrimeNG version 12.0.1 along with its Table component to showcase data within my Angular application. In a separate @Component, I have included the <p-table> in the HTML template. Within the <p-table>, there are variou ...

Retrieve a variety of items and pass them to a view using the mssql module in Node

I'm facing an issue while trying to retrieve data from multiple tables and pass them to my view. Below is the snippet of code I've written that's causing the error. router.get('/', function(req, res, next) { sql.connect(config ...

Unlimited scrolling feature implemented in a specified container using AngularJS

Does anyone have experience with using angularjs infinite scroll within an inner DIV instead of just the browser window? I'm trying to implement infinite scroll within a specific content wrapper that has its own scrollbar. The main page is fixed and ...

Converting JSON DateTime objects to local time in JQuery without considering timezones

I am struggling with parsing a JSON DateTime object using moment.js. Despite trying various methods recommended on Stackoverflow, nothing seems to work in my case. In my application, I save DateTime values in UTC format and when displaying them, I need to ...

I am having issues with the Load More Posts Ajax Button on my WordPress site and it is

I'm trying to display more posts when a button is clicked. Upon inspecting and checking the network, everything seems to be working fine, or at least that's what I assume. https://i.sstatic.net/44VS1.jpg https://i.sstatic.net/KEkiz.jpg I&apos ...

Angular binding of variable names beginning with numbers

Currently in my Angular 4 project, I am utilizing the interpolation syntax below: {{variable.24h_volume}} Upon implementation, an error is thrown stating: Unexpected token '0.24' at column 5 in [{{variable.24h_volume}}] in ng:///AppModule/Comp ...