今天,我在我的私人角度应用程序中遇到了细节组件问题。我要存档的只是获取可观察用法的客户对象的详细信息,然后将它们传递给HTML组件。
Customer-single.component.ts
@Component({
selector: 'app-customer-single',
templateUrl: './customer-single.component.html',
styleUrls: ['./customer-single.component.css']
})
export class CustomerSingleComponent implements OnInit {
customer$: Observable<CustomerDetails>;
constructor(private customerService: CustomerService,
private activatedRoute: ActivatedRoute,
private router: Router) {
}
ngOnInit() {
const id = this.activatedRoute.snapshot.params['id'];
this.customerService.getOne(id).subscribe(
data => console.log(this.customer$ = data),
error => console.error(error.message));
}
}
Customer-single.component.html
<p>
{{(this.customer$ | async).name}}
</p>
<p>
{{(this.customer$ | async).email}}
</p>
在“详细信息”按钮后,单击主要客户部分:
<div>
<h1 class="text-primary h1 my-5">Customers list below:</h1>
</div>
<div>
<table class="table table-striped table-primary">
<thead>
<tr>
<th scope="col">No.</th>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Phone number</th>
<th scope="col">Email</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let customer of ( customers$ | async ); let i = index">
<td scope="row">{{i + 1}}</td>
<td>{{customer.name}}</td>
<td>{{customer.surname}}</td>
<td>{{customer.phoneNumber}}</td>
<td>{{customer.email}}</td>
<td>
<a [routerLink]="['/companies/modify', customer.id]" class="btn btn-info mr-2">Modify</a>
<a [routerLink]="['./single', this.customer.id]" class="btn btn-secondary mr-2">Details</a>
<a class="btn btn-danger mr-2" (click)="onRemove(company.id)">Remove</a>
</td>
</tr>
</tbody>
</table>
</div>
<div>
<a class="btn btn-outline-primary" routerLink="add">Add new customer</a>
</div>
我收到两个错误:
TypeError: Cannot read property 'name' of null
和
InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'
以上,我记录了一个将值分配给customer $的过程,并且所需参数name
不为空。
我意识到它会将与主组件中显示的参数相同的参数传递给detail组件,但这只是一个说明性示例。
预先感谢您的帮助。
答案 0 :(得分:0)
尝试更改以下代码:
const id = this.activatedRoute.snapshot.params['id'];
this.customerService.getOne(id).subscribe(
data => console.log(this.customer$ = data),
error => console.error(error.message));
对此:
const id = this.activatedRoute.snapshot.params['id'];
this.customerService.getOne(id).subscribe(
data => {
console.log(data);
this.customer$ = data
},
error => {
console.error(error.message);
});
上面的代码有一个订阅,它将等待结果;
因此在模板中不必使用管道异步:
尝试为此进行更改:
<p>
{{customer$?.name}}
</p>
<p>
{{customer$?.email}}
</p>
祝你好运