在 Angular 应用程序中直接在组件 HTML 中获取会话变量?
Get session variable directly in component HTML within Angular application?
有没有一种方法可以直接在组件 HTML 中获取并显示会话变量的值,而无需将会话变量的值分配给局部变量?
类似于:
<span>{{sessionStorage.getItem('name')}}</span>
Angular中提到documentation, the expression context in the template is the component instance. Since sessionStorage是window
对象的成员,不能在模板中直接引用:
Template expressions cannot refer to anything in the global namespace,
except undefined
. They can't refer to window
or document
.
您可以通过将 sessionStorage
分配给组件 class:
的 public 属性 使其在模板中可用
export class MyComponent {
public sessionStorage = sessionStorage;
}
并参考模板中的属性:
<span>{{sessionStorage.getItem('name')}}</span>
有关演示,请参阅 this stackblitz。
有没有一种方法可以直接在组件 HTML 中获取并显示会话变量的值,而无需将会话变量的值分配给局部变量?
类似于:
<span>{{sessionStorage.getItem('name')}}</span>
Angular中提到documentation, the expression context in the template is the component instance. Since sessionStorage是window
对象的成员,不能在模板中直接引用:
Template expressions cannot refer to anything in the global namespace, except
undefined
. They can't refer towindow
ordocument
.
您可以通过将 sessionStorage
分配给组件 class:
export class MyComponent {
public sessionStorage = sessionStorage;
}
并参考模板中的属性:
<span>{{sessionStorage.getItem('name')}}</span>
有关演示,请参阅 this stackblitz。