How to import dynamic XHR content into a template dynamically?

北慕城南 提交于 2019-12-11 04:05:21

问题


I fetch my Dashboard HTML data using the following code which is executed when I click a button:

fetchDashboard() {
    const requestOptions: Object = {
      headers: new HttpHeaders().append('Authorization', 'Bearer <tokenhere>'),
      responseType: 'text'
    }
    this.http.get<string>('http://localhost:3000/avior/dashboard',
        requestOptions)
            .subscribe(response => {
                   this.dashboardData = response;
            }
    );
}

I have multiple components setting up my view and I want to modify one of the views completely from scratch to contain the fetched content, how do I do that?

As recommended here I tried using <div [innerHtml]="dashboardData"></div> without any avail.


UPDATE

My admin nav.ts looks like this:

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-avior-admin-nav',
  templateUrl: './avior-admin-nav.component.html',
  styleUrls: ['./avior.component.css']
})
export class AviorAdminNavComponent implements OnInit {

  dashboardData: string;


  constructor(private http: HttpClient) { }

  ngOnInit() {console.log('dashboardData: ', this.dashboardData);


  }
  fetchDashboard() {

    const requestOptions: object = {
      // tslint:disable-next-line: max-line-length
      headers: new HttpHeaders().append('Authorization', 'Bearer tokenhere'),
      responseType: 'text'
    };
    this.http.get<string>('http://localhost:3000/avior/dashboard',
        requestOptions)
            .subscribe(response => {
                   console.log(response);
                   this.dashboardData = response;
            }
    );
}

}

My dashboard component.ts looks like this:

import { Component, OnInit, Input } from '@angular/core';
import { User } from '../models/user.model';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})

export class DashboardComponent implements OnInit {
  /* @Input() */ dashboardData: string;
  user: User;
  // dashboardData: string;
  constructor() { }

  ngOnInit() {
    console.log('dashboardData in dashboard comp: ', this.dashboardData);
  }

  canDeactivate(): Promise<any> | boolean {
    if (localStorage.getItem('currentUserToken') === 'token') {
            return (true);
          } else {
            return (false);
          }

}
}

My dashboard component HTML looks like this:

<p>
  Welcome and please replace me with dashboard text!
</p>
<div [innerHtml]="dashboardData"></div>
<div *ngIf="this.dashboardData" [innerHtml]="dashboardData">Test {{this.dashboardData}}</div>

My admin nav HTML looks like this:

                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        Administration
                    </a>
                    <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                        <a class="dropdown-item" (click)=fetchDashboard()>Dashboard</a>
                        <a class="dropdown-item" [routerLink]="['/avior/users']">Users</a>
                        <a class="dropdown-item" [routerLink]="['/avior/workflows']">Workflows</a>
                        <div class="dropdown-divider"></div>
                        <a class="dropdown-item" [routerLink]="['/avior/system']">System</a>
                    </div>
                </li>

My avior.component.html looks like this:

<div>
    <router-outlet></router-outlet>
</div>

My app.component.html looks like this:

<!-- Navigation -->
<div class="navigation">
    <nav class="navbar navbar-expand-lg fixed-top navbar-dark bg-dark">

        <!-- Brand - Logo + Title -->
        <a class="navbar-brand">
            <img width="25" src="../assets/images/app_logo.jpg">
            <a class="navbar-brand" [routerLink]="['/avior/dashboard']">&nbsp;&nbsp;=== Application ===</a>
        </a>

        <!-- Menu -->
        <div class="collapse navbar-collapse" id="navbarSupportedContent">

            <!-- Menu left -->
            <ul class="navbar-nav mr-auto">

                <!-- Menu App -->
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        Application
                    </a>
                    <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                        <a class="dropdown-item" [routerLink]="['/carinae/list-content']">Mask 1</a>
                        <a class="dropdown-item" [routerLink]="['/carinae/tree-tab']">Mask 2</a>
                        <div class="dropdown-divider"></div>
                        <a class="dropdown-item" [routerLink]="['/carinae/app-settings']">App Settings</a>
                    </div>
                </li>

                <!-- Menu Admin-->
                <app-avior-admin-nav></app-avior-admin-nav>
            </ul>

            <!-- Menu right -->
            <app-avior-user-nav></app-avior-user-nav>
        </div>
    </nav>
</div>

<!-- Content / Output -->
<div class="content">
    <router-outlet></router-outlet>
</div>


回答1:


If the response of the request returns HTML as a string, you'll just have to correct your binding to the template. Replace :

<div [innerHtml]="this.dashboardData"></div>

by

<div [innerHTML]="dashboardData"></div>

If you check the link provided in your question, a binding in HTML never calls the this keyword.

EDIT

Now that the code is included, your admin-nav component gets the dashboardData, and stores it in its dashboardData member. But it was never transmitted to your dashboardComponent. Now :

DashboardComponent.ts : Uncomment the @Input().

DashboardComponent.html : Correct *ngIf="dashboardData"

Nav.html : add a <app-dashboard [dashboardData]="dashboardData"></app-dashboard>



来源:https://stackoverflow.com/questions/58952820/how-to-import-dynamic-xhr-content-into-a-template-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!