Updating an Observable in Angular 4 using HttpClient's get method

Seeking assistance in updating an observable retrieved in html format from an API call.

If anyone has any insights on how to achieve this, your help would be greatly appreciated.

The corresponding html (in another component) is:

<common-content [theme]="theme" ></common-content>

and the respective component code is as follows:

import { Component, OnInit, Input } from '@angular/core';
import { Http, Response } from '@angular/http';
import { ThemeModel } from '../../models';
import 'rxjs/add/operator/toPromise';

@Component({
  selector: 'common-content',
  template: `<div innerHTML = "{{innerHtml}}"></div>`
})

export class CommonContentComponent implements OnInit {
    @Input() page: string;
    @Input() theme: ThemeModel;
    innerHtml: string;

    constructor(private http: Http) {
    }

    ngOnInit() {
        this.populatePage();
    }

    populatePage(){
        let thisUrl = 'myPage.html';
        this.http.get(thisUrl).subscribe(f => {
            var content = <string>f['_body'];
            this.innerHtml = content.replace("{{theme.Name}}", this.theme.name);
            }, (error) => {
                let e = error;
            }, () => {
        });
    }
}

The goal is for the observable to update automatically instead of using "replace". Attempts have been made with both subscribe and promises, but syntax issues persist.

If you have any suggestions or solutions, please share them. Your assistance is appreciated.

Thank you.

Answer №1

1) It's not clear what your goal is. From what I can gather, you want to update the DOM upon success. 2) Avoid using innerHTML and consider using interpolation or ngModel along with a sanitizer instead. 3) Another option would be to develop a custom reusable directive for this purpose.

One possible approach:

1) Create a sanitization pipe:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({
  name: 'safeHtml'
})
export class SafeHtmlPipe implements PipeTransform {
  
  constructor(private sanitizer: DomSanitizer) { }
  
  transform(style) {
    return this.sanitizer.bypassSecurityTrustHtml(style);
  }
}

2) Utilize it as follows:

<div class="card_description" [innerHTML]="scenarioStepDataDesc | safeHtml"></div>

where scenarioStepDataDesc represents your HTML content.

3) Implement a shared module for pipes and other reusable components/directives

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MaterialModule } from '../material/material.module';
import { BlockUIModule } from 'ng-block-ui';
import { AutoCompleteComponent } from './components/autoComplete/autoComplete.component';
import { DialogDataComponent } from './components/dialog/dialog.component';
import { SafeHtmlPipe } from './pipes/safeHtml.pipe';

@NgModule({
  imports: [CommonModule, FormsModule, MaterialModule, BlockUIModule, ReactiveFormsModule],
  exports: [
    CommonModule,
    FormsModule,
    MaterialModule,
    BlockUIModule,
    ReactiveFormsModule,
    AutoCompleteComponent,
    DialogDataComponent,
    SafeHtmlPipe
  ],
  declarations: [AutoCompleteComponent, DialogDataComponent, SafeHtmlPipe]
})
export class SharedModule { }

Enjoy :)

Answer №2

If you want to update your code snippet, consider changing <string> f['_body']; to <string>f.text(), and also updating innerHTML = "{{innerHtml}}" to [innerHTML]="view". You can refer to the Plnkr link provided below to see an example of how it works.

this._http.get(link).subscribe(f => {
     this.loading = false;
            var content = <string>f.text();
            this.view = content.replace("{{theme.Name}}", this.theme.name);
            }, (error) => {
              this.loading = false;
              console.error(error);
                alert(error);
            });

This is what the template looks like:

content <button (click)="open('external.html')">Open Page</button>
      <strong *ngIf="loading">LOADING...</strong>
      <div [innerHTML]="view"></div>

The contents of external.html are simple:

me playing around with this theme with name 
<b>
  {{theme.Name}}
</b>

You can access the running Plnkr here

For processing String interpolation as if the content were in the same parent template, and binding it to the template scope (similar to Angular 1's ng-include), check out this helpful answer for Angular 4 and above versions.

using Angular 4.0.0-beta.6's ngComponentOutlet.

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

Steps for updating the clientId and authority values in MSAL configuration after they have already been read

Currently, I am utilizing Azure AD B2C for a multi-tenant application. The user starts by inputting their email, followed by selecting an option from a drop-down list populated based on the tenant they are associated with (tenant1, tenant2, tenant3). If th ...

Calculate the total of JSON objects while eliminating duplicates in an array

Below is an array of objects: const lineItems = [ { "lineNumber": "0", "item": "1496", "itemDesc": "wertyuiasdfghj", "qualityReceiptHold": "N", ...

The cache-control header is not being included in the response header in the express app

I am facing an issue where the Cache-Control header is not getting added to the document request in my express / node server. My code successfully adds other headers, but for some reason, it fails when trying to add Cache-Control and I'm unsure why. ...

unable to log out firebase user

Currently, I am attempting to sign out the user who is already signed in within my Angular app. Here is my client service code: export class AuthClientService { public register(email: string, password: string): Observable<Object> { retu ...

Conserving node.js native imports for Electron with rollup

I am working on a project using Electron, Svelte, and Typescript. Initially, I used a specific template from here, but it restricted access to node.js built-in imports like fs for security reasons in the browser/electron frontend. However, I do not requir ...

Why would npm be unable to locate a file, potentially leading to an error? Could the lack of contents in my node_modules subfolder be the root cause of this issue?

I'm encountering an issue while attempting to execute npm install in the angular project directory obtained from ASP.NET Boilerplate. The error I'm facing is related to npm's inability to locate a specific file. D:\Dev\AspNetBoiler ...

Accessing instance variables from a chained observable function in Angular 2/Typescript

Currently, I am utilizing Angular2 along with Typescript. Let's assume that there is a dummy login component and an authentication service responsible for token authentication. In one of the map functions, I intend to set the variable authenticated as ...

Bidirectional synchronization with Angular 6 reactive forms

I'm currently working on building a complex reactive form that includes nested components populated with data objects. The functionality I'm aiming for is similar to the two-way data binding in template-driven forms: when a user modifies an inpu ...

In React TS, the function Window.webkitRequestAnimationFrame is not supported

I'm facing an issue where React TS is throwing an error for window.webkitRequestAnimationFrame and window.mozRequestAnimationFrame, assuming that I meant 'requestAnimationFrame'. Any suggestions on what to replace it with? App.tsx import Re ...

Tips for updating values in an Angular model and pushing it to an array with the specified index

I am currently facing an issue with my Angular Model as I attempt to add it to an array in order to generate repeated fields. The purpose of this array is to then be looped through in order to create HTML fields within a component. However, during the proc ...

Merge mocha with Typescript, and include the watch feature

For my project, I have set up mocha to test my Typescript code. The issue arises when running the command: mocha ts/test --compilers ts:typescript-require Every time I make a change, it fails with an error message like this: error TS2307: Cannot find mo ...

Managing simultaneous asynchronous updates to the local state

There is a scenario where a series of asynchronous calls are made that read from a local state S, perform certain computations based on its current value, and return an updated value of the local state S'. All these operations occur at runtime, with ...

Conditions are in an angular type provider with AOT

I am facing an issue with my Angular project that is compiled using AOT. I am trying to dynamically register a ClassProvider based on certain configurations. The simplified code snippet I am currently using is below: const isMock = Math.random() > 0.5; ...

Issue may arise when using custom directive in conjunction with mat-menu-item directive, potentially leading to malfunction. The root

Attempting to create a custom directive that will disable a button within a mat-menu and execute additional logic. Simplifying the code, here is the HTML template: <mat-menu #editMenu="matMenu"> <ng-template matMenuContent> <butto ...

How come the Handsontable CSS styles are not being used on my Angular frontend?

I am currently facing an issue while trying to integrate a Handsontable into my Angular frontend. I was able to successfully implement the basic example from in a new Angular project. However, when I tried to add the exact same code to my existing reposit ...

Is there a method to reference a class before it has been defined?

I have a working code snippet that currently appears like this: import { OtherClass } from "other-class" class VeryLongClass { } OtherClass.run(VeryLongClass); However, I would like to rearrange it to look like this: import { OtherClass } fro ...

Various gulp origins and destinations

I am attempting to create the following directory structure -- src |__ app |__ x.ts |__ test |__ y.ts -- build |__ app |__ js |__ test |__ js My goal is to have my generated js files inside buil ...

The Vue router fails to load when using create-vue@3

I've been experimenting with the Vue Router, but it's not giving me the expected outcome. While following the tutorial on https://router.vuejs.org/guide/, I found that if I use the CDN and place it in a standalone HTML file, it works fine. Howev ...

Activate the button when a checkbox within a looping structure is selected using Angular 5

As a relatively new Angular 5 user, I am working with a button that looks like this: <button *ngIf="type!='invoices' && this.action==='edit'" disabled (click)="genera(fields.termini)" class="ml-16 mat-raised-button mat-accen ...

Stop the MatSort feature from activating when the space key is pressed in Angular Material

I am currently using angular material tables and have implemented filters for each column. The filter inputs are located in the row header of each column, which is working fine. However, I am facing an issue where whenever I type and press the space key, ...