TypeError: Невозможно прочитать свойство 'name' из null с помощью InvalidPipeArgument: '[object Object]' для канала 'AsyncPipe' - PullRequest
0 голосов
/ 14 мая 2019

сегодня я столкнулся с проблемой деталей в моем частном угловом приложении. Все, что я хочу заархивировать, это получить подробную информацию о клиентском объекте с видимым использованием и, в конце концов, передать их компоненту HTML.

Клиент-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));
  }

}

Клиент-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'

Выше я регистрировал процесс присвоения значений клиенту $ наблюдаемый и обязательный параметр name не равен нулю.

Я понимаю, что он передает компоненту деталей тот же параметр, который отображается в основном компоненте, но это только иллюстративный пример.

Заранее спасибо за помощь.

1 Ответ

0 голосов
/ 14 мая 2019

Попробуйте изменить следующий код:

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>

удачи

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...