Angular 7如何将嵌入式JS脚本包含到组件中? [英] Angular 7 how to include inline JS script into component?

查看:174
本文介绍了Angular 7如何将嵌入式JS脚本包含到组件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的Angular 7项目中安装places.js库,但是遇到了问题。我已将以下脚本添加到 index.html文件中

 < script src = https:// cdn。 jsdelivr.net/npm/places.js@1.16.4\"</script> 
< script>
varplacesAutocomplete = places({
appId:'myAppId',
apiKey:'myApiKey',
容器:document.querySelector('#addressInput')
} );
< / script>

,但是只有在我拥有



< pre> <输入类型=搜索 id =地址输入占位符=我们要去哪里? />

在我的 index.html中。我试图将此输入包含到我的组件中,但是它不起作用,并且出现错误

  places.js@1.16。 4:1未捕获的错误:Algolia位置:容器必须指向< input>元件。 

是否可以附加此脚本并使其起作用?在文档中没有关于打字稿的任何内容。我也尝试过npm install和

  import * from'places.js'

,但是有相同的问题。

解决方案

更好地将其嵌入到Angular组件中使用:

 从 @ angular / core导入{Component,OnInit}; 
从 places.js导入位置;

@Component({
选择器: app-root,
templateUrl: ./ app.component.html,
styleUrls:[ ./ app.component.css]
})
导出类AppComponent实现OnInit {
title = my-app;

ngOnInit():void {
const placeAutocomplete = place({
appId: appId,
apiKey: appKey,
容器: document.querySelector(#address-input)
});
}
}

您也应该将此内容放入 polyfill.js 以使其起作用:

 (任何窗口)。 = {
env:{调试:未定义}
};

(任意窗口).global = window;


I'd like to install places.js library into my Angular 7 project, but I have a problem. I've included following script into my 'index.html' file

 <script src="https://cdn.jsdelivr.net/npm/places.js@1.16.4"></script>
  <script>
    var placesAutocomplete = places({
      appId: 'myAppId',
      apiKey: 'myApiKey',
      container: document.querySelector('#addressInput')
    });
  </script>

but it is working only when I have

<input type="search" id="address-input" placeholder="Where are we going?" />

in my 'index.html'. I've tried to include this input into my component but it's not working and I have an error

places.js@1.16.4:1 Uncaught Error: Algolia Places: 'container' must point to an <input> element.

Is it possible to attach this script and make it working? In the documentation there is nothing about typescript. I've also tried to npm install and

import * from 'places.js'

but have same issue. Could someone help?

解决方案

Better to use it embedded in an Angular Component:

import { Component, OnInit } from "@angular/core";
import places from "places.js";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  title = "my-app";

  ngOnInit(): void {
    const placesAutocomplete = places({
      appId: "appId",
      apiKey: "appKey",
      container: document.querySelector("#address-input")
    });
  }
}

you should place also this in your polyfill.jsin order to make it work:

(window as any).process = {
  env: { DEBUG: undefined }
};

(window as any).global = window;

这篇关于Angular 7如何将嵌入式JS脚本包含到组件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆