将变量从index.html发送到app.component.ts

Far*_*iba 1 javascript angular

我可以将变量从index.html发送到app.component.ts吗?我在index.html中有这个脚本,并且我想在将查询参数删除到app.component.ts之前发送可变的url

  <script type="text/javascript">
        var url = window.location.toString();
       if(url.indexOf("?") > 0) {
          var sanitizedUrl = url.substring(0, url.indexOf("?"));
          window.history.replaceState({}, document.title, sanitizedUrl);
        }
      </script>
Run Code Online (Sandbox Code Playgroud)

Nik*_*vic 5

当然可以。我做了一个小演示来向您展示如何操作。

  1. 您所要做的就是像在index.html 中那样包装您的代码。
  2. 您必须声明该变量。您可以在组件内部执行此操作
import { Component } from '@angular/core';

// notice that foo is inited in index.html
declare var foo;

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
Run Code Online (Sandbox Code Playgroud)

或在typings.d.ts. 我建议在 types.d.ts 中声明它。如果您使用 angular-cli,并且我假设它位于src/app/typings.d.ts.

declare var foo: any;
Run Code Online (Sandbox Code Playgroud)

就是这样。您可以在应用程序中的任何位置使用变量。