在我的应用程序中,我有一个组件将用户对象发送到另一个组件,它正确接收它,如成功的console.log(user.vendorname)所证明的那样,按预期返回,但它不会显示在html上。 html文件
<div class="col-centered">
<h1 *ngIf="user | async">Welcome {{user.vendorname}}</h1>
</div>
组件文件
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
}
}
答案 0 :(得分:2)
您需要将observable传递给异步管道。 异步管道的想法是短版本,所以你不要把observable分配给任何变量
执行类似
的操作public get user() Observable<User> {
return this.loginService.getMessage();
}
或
public getUser() Observable<User> {
return this.loginService.getMessage();
}
并像
一样使用它<your-component [yourInput]="user | async"></your-component>
or
<your-component [yourInput]="getUser | async"></your-component>
建议使用它,因为它会自动取消订阅销毁。 您需要注意以下情况:
在单个模板中使用async时,您会收到两个请求:
(user | async).id
(user | async).name
答案 1 :(得分:1)
async
管道仅适用于Observable,此处user
对象已分配value
。要使其适用于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()
}
答案 2 :(得分:0)
试试这个:
<html>
<head>
</head>
<body>
<input type='text' name='name' id='name' maxlength="50" value=<?php echo $_POST["name"]?> />
<body/>
</html>