如何在 Angular2 中获取元值

How to get meta value in Angular2

如何从 Angular2 中的 HTML head 获取元值?

例如,我有项目的 HMTL,我想获取元名称 "userId"。

 <!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>SampleProject</title>
    <base href="/">
    <meta name="userId" value="12345">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>

<body>
    <app-root>Loading...</app-root>
</body>

</html>
document.querySelector('meta["userId"]').getAttribute('value')

Angular2 对此没有特别支持。

如果您试图避免直接 DOM 访问,您可以在开始 Angular2 之前阅读此内容并使用 DI 将其传递给 Angular。

var userId =     document.querySelector('meta["userId"]').getAttribute('value');

// @Injectable(),  @Component(), or @Directive()
class ServiceOrComponent {
  constructor(@Inject('userId') private userId:string) {}
}

@NgModule({
  providers: [{provide: 'userId', useValue: userId]}
  ....
})
export class AppModule() 

您还可以使用 OpaqueToken

而不是 'userId' 字符串