【问题标题】:How to pass @Input() decorator value to its html file?如何将 @Input() 装饰器值传递给它的 html 文件?
【发布时间】:2018-10-30 05:13:28
【问题描述】:

我有主 app.component.ts,从这里我将 currentstatus 变量传递给 chid 组件(导航栏组件),它是 navbar.component.ts,我已经使用 @input() 将值传递给导航栏组件装饰器,但我遇到问题如何将输入装饰器的这个值传递给 navbar.component.html?

我的主要app.component.ts

export class AppComponent {

      public currentstatus: any;

      constructor(private authService:LoginAuthService,private router:Router){
           this.currentstatus=this.authService.getStatus().
           subscribe(currentstatus => {
            this.currentstatus=currentstatus;
           })
      }

      logout(){
        localStorage.removeItem('currentUser');
        this.router.navigate(['login']);
      }

从这里我正在传递这个当前状态

我的app.component.html

<div id = "wrapper">
    <div class="main-page">
<app-navbar [currentstatus]="currentstatus" ></app-navbar>

<router-outlet></router-outlet>
<app-footer></app-footer>
</div>
</div>

这里我已将当前状态传递给 navbar.component.ts

export class NavbarComponent implements OnInit {

    @Input() currentstatus:any;


   constructor(){

  }
  ngOnInit() {
  }

  logout(){

  }
}

现在如何将此当前状态传递给 navbar.component.html???

【问题讨论】:

  • “我遇到问题如何通过...”是什么意思。你在控制台有错误吗?在我看来,您正在使用正确的方式将值传递给子组件。
  • 作为一般建议,您可以将加载部分放在 AppComponent 的 ngOnInit 函数中(并将类标记为 implements OnInit)。但我认为这不会解决您的问题。
  • Jsut 打印所以:{{currentstatus}}
  • 是的,如何使用 @Input() currentstatus:any;在 ngOnInit 函数内部。我对此感到困惑
  • 哦,我明白了,让我写一个答案。在致电服务之前摆脱this.currentstatus=

标签: javascript angular angular6


【解决方案1】:

你的错误是你正在做类似abc = service.get().subscribe(result =&gt; abc = result;}) 的事情

(您试图将currentstatus both 设置为整个订阅作为订阅的结果)

只需像这样使用您的服务:

将请求的结果分配给 currentstatus :

可能性一:

应用组件:

this.authService.getStatus().subscribe(
    result =>  { this.currentstatus = result; });

可能性2:

或者您可以使用来自 Angular 的 async 管道为您进行订阅,在这种情况下,父应用程序中的 currentstatus 应该是整个 Observable(没有订阅),这将给出类似:

AppComponent.ts :

// assign the Observable to your variable currentstatus
this.currentstatus = this.authService.getStatus();

AppComponent.html:

<app-navbar [currentstatus]="currentstatus | async"></navbar>

注意:

注意这两种情况:一般来说,最好的做法是在 ngOnInit 函数而不是构造函数中执行服务调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    相关资源
    最近更新 更多