首页 > 解决方案 > 为什么我在组件中导入的 js 不起作用?

问题描述

我在 mt angular navbar 中有 Jquery 函数,一旦我将链接路由到另一个组件,这些函数似乎不起作用,但这些函数对我的导航栏很重要,所以我把它们放在我添加到我的角度的 js 文件中.json 脚本字段,因此即使我路由到另一个组件也可以加载它,但现在我不知道为什么当我尝试使用包含我的 jquery 代码的函数时它不起作用。

navabr.component.ts

import {Component, OnInit} from '@angular/core';
import {AuthService} from "../auth.service";
import {clientType} from "../clientType";
import {navbarutil} from './navbarUtilities.js';
declare var $;

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


  constructor() {
  }

  ngOnInit(): void {
    navbarutil.switchstate(); //launch with a collapsed navbar
    navbarutil.unwindOnCollapsed();
    navbarutil.buttonSwitch();
  }

 
}

navabrUtilities.js

function unwindOnCollapsed() {
  $(document).ready(function() {
    $('a.collapsed').click(() => {
      console.log('hey '+this.isOpen());
      if (!(this.isOpen())) {
        this.switchstate()
      }
    });
  });
}

function buttonSwitch() {
  $(document).ready(function() {
    $('#bouttonmenunavbar').click(() => {
      this.switchstate();
    });
  });
}

function switchstate() {
  $(document).ready(function() {
    console.log('yes');
    $('.sidebar').toggleClass('fliph');
    $('.innerlist').collapse('hide');
  });
}

function isOpen() {
  return $('.sidebar').hasClass('fliph');
}

角.json

"scripts": [
           "./src/app/navbar/navbarUtilities.js"
            ]

你能帮我找到如何让它们工作吗?

标签: javascriptjqueryangularangular-cli

解决方案


function buttonSwitch() {
  $(document).ready(function() {
    $('#bouttonmenunavbar').click(() => {
      this.switchstate();
    });
  });
}

这个问题可能就在这里this.switchState()。的上下文this是文档的功能。您必须编写一个箭头函数才能获得包含方法的类的 this switchState

function buttonSwitch() {
  $(document).ready(() => { // here is the modification
    $('#bouttonmenunavbar').click(() => {
      this.switchstate();
    });
  });
}

推荐阅读