在HTTP请求完成并在Angular中渲染后调用JS函数

问题描述 投票:0回答:1

我想从外部JS文件中调用一个函数来处理组件中的元素(来自HTTP请求的内容)。脚本加载得很好,但在HTTP响应之前,我无法使用我的函数。这是我的代码。

import { Component, OnInit } from '@angular/core';
import { HttpService } from '../http.service'
import * as $ from 'jquery';
declare const myFunc: any;


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

  items: object;

  constructor(private _http: HttpService) { }

  ngOnInit(): void {
    this._http.myList().subscribe(
      data =>{
        this.items= data;
        console.log(this.items);
      },    
      myFunc(),
    )
  } 
}

有什么办法能让我在加载完所有组件的数据后再加载我的脚本?

谢谢!我想从HTTP响应中调用一个函数。

javascript jquery angular angular8
1个回答
0
投票

如果我对你的问题理解正确的话,你应该利用的是 ngAfterViewInit. 这个方法在你的视图初始化后就会被调用,这个时候从api返回的数据就会被html使用。

export class HomeComponent implements OnInit, AfterViewInit {

    items: object;

    constructor(private _http: HttpService) { }

    ngOnInit(): void {
      this._http.myList().subscribe(
        data => {
          this.items = data;
          console.log(this.items);
        }
      )
    }
    ngAfterViewInit() {
      myFunc();
    }
  }

你当前的func调用没有意义,因为它将作为@Robin指向的subscribe的错误回调函数工作。

ngAfterViewInit

© www.soinside.com 2019 - 2024. All rights reserved.