Angular7 如何将内联JS脚本包含到组件中?

Angular 7 how to include inline JS script into component?

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

 <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>

但它只有在我有

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

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

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

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

import * from 'places.js'

但有同样的问题。有人可以帮忙吗?

我尝试了你的方法,但没有成功。

您需要下载 places.js 文件并将其放入脚本文件夹。

在生成器 > 脚本中更新 angular.json 文件

 "build": {
      "builder": "@angular-devkit/build-angular:browser",
      "options": {
        ...
        "assets": [...],
        "styles": [...],
        "scripts": [
          "script/places.js"
        ]
      },

您需要将所有 Place 代码保存在一个组件中并在 ngOnItit() 上对其进行初始化。

import { Component, OnInit } from '@angular/core';
import * as Places from 'places';

@Component({
  selector: 'my-app',
  templateUrl: './yourComponent.html'
})
export class AppComponent implements OnInit  {

  ngOnInit(){
    Places({
      appId: 'myAppId',
      apiKey: 'myApiKey',
      container: document.querySelector('#addressInput')
    });
  }
}

yourComponent.html:

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

最好将它嵌入到 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;

好吧,根据我的观察,这需要在调用之前加载输入,并且您在加载输入之前将其附加到索引。 这当然不行

var placesAutocomplete = places({
  appId: 'myAppId',
  apiKey: 'myApiKey',
  container: document.querySelector('#addressInput')
});

几乎没有其他方法可以做到这一点,但就我而言,我会创建一个服务,比如

declare var places:any;
@Injectable({providedIn:'root'})
export class PlacesServices {
      setup(){
        var placesAutocomplete = places({
        appId: 'myAppId',
        apiKey: 'myApiKey',
        container: document.querySelector('#addressInput')
       });
      }

}

然后将其注入到您的组件中,并且仅在加载具有正确 ID 的输入时调用它,您需要 ngAfterViewInit 以确保加载视图

ngAfterViewInit(){
   this.placesService.setup();
  //i would be calling the setup here on the component with the input
}

js 脚本可以添加到 index.html 或者就像 Hien 回答指出的那样。

我刚刚输入,可能有一些错字,但你应该明白了。希望对你有用!