简体   繁体   English

Angular 2异步数据绑定不起作用

[英]Angular 2 async data binding not working

In my application I have one component sending a user object to another component and it receives it correctly as proven by successful console.log(user.vendorname) returning as expected but it won't show up on the html. 在我的应用程序中,我有一个组件将用户对象发送到另一个组件,并且通过成功的console.log(user.vendorname)返回期望的方式证明它可以正确接收它,但是不会显示在html上。 The html file html文件

<div class="col-centered">
<h1 *ngIf="user | async">Welcome {{user.vendorname}}</h1>
</div>

The component file 组件文件

import { User } from '../User';
import { AccountInfo } from './../AccountInfo';
import { LoginService } from './../login.service';
import { Component, OnInit, AfterViewInit, OnDestroy } from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/operator/map';






@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {

user: User;
subscription: Subscription;



  constructor(route: ActivatedRoute, private loginService: LoginService) {



   }

  ngOnInit() {
    this.subscription = this.loginService.getMessage().subscribe(data => {

       this.user = data;
       console.log(this.user.vendorname);
    });
  }



  AfterViewInit(){

  }
ngOnDestroy() {
        // unsubscribe to ensure no memory leaks


    }

}

You need to pass observable to async pipe. 您需要将observable传递给异步管道。 async pipe idea is for short version so you dont neet to assign observable to any variable 异步管道的想法是简短的版本,因此您无需为任何变量分配observable

Do something like 做类似的事情

public get user() Observable<User> {
  return this.loginService.getMessage();
}

or 要么

public getUser() Observable<User> {
  return this.loginService.getMessage();
}

And use it like 并像这样使用

<your-component [yourInput]="user | async"></your-component>
or
<your-component [yourInput]="getUser | async"></your-component>

It is recomended because it automatically unsubscribes on destroy. 推荐它是因为它在销毁时会自动退订。 There are exceptions where you need to watch out for: 有一些例外情况需要您注意:

When you use async in single template like you would get two requests: 当您在单个模板中使用异步时,您将收到两个请求:

(user | async).id
(user | async).name

docs docs

async pipe works only on Observable, here user object has value assigned to. async管道仅适用于Observable,此处为user对象分配了value To make it works with async pipe assign observable to user 为了使其与async管道一起工作,可以将观察分配给user

import { Observable } from 'rxjs/Observable';//don't miss this import.

user: Observable<User>; //add declaration for user

ngOnInit() {
  this.user = this.loginService.getMessage()
}

Try this: 尝试这个:

public get user() Observable<User> {
  return this.loginService.getMessage();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM