javascript - Angular 7 如何將內聯 JS 腳本包含到元件中?
我想將 places.js 庫安裝到我的 Angular 7 專案中,但我遇到了一個問題。我已經在我的 'index.html' 文件中包含了以下腳本
<script src="https://cdn.jsdelivr.net/npm/[email "></script>
<script>
var placesAutocomplete = places({
appId: 'myAppId',
apiKey: 'myApiKey',
container: document.querySelector('#addressInput')
});
</script>
但它只在我有的時候才工作
<input type="search" id="address-input" placeholder="Where are we going?" />
在我的 'index.html' 中。我試圖將這個輸入包含到我的組件中,但它不起作用,而且我出現了錯誤
[email :1 Uncaught Error: Algolia Places: 'container' must point to an <input> element.
有可能附加這個腳本並使它運作嗎?在文件中沒有關於 TypeScript 的任何內容。我也嘗試過 npm install 並
import * from 'places.js'
但是還是一樣的問題。有人能幫忙嗎?
答案#1
最好將它嵌入在 Angular 元件中使用:
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")
});
}
}
你也應該把這個放到你的 polyfill.js 中以使其生效:
(window as any).process = {
env: { DEBUG: undefined }
};
(window as any).global = window;
答案#2
我試過你的方法,但沒有成功。
你需要下載 places.js 文件並放到一個腳本資料夾中。
在 builder > scripts 更新 angular.json 文件
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
...
"assets": [...],
"styles": [...],
"scripts": [
"script/places.js"
]
},
