Код Visual Studio в Angular: Не удается прочитать свойство undefined, Как исправить? - PullRequest
0 голосов
/ 08 ноября 2019

Как мне взять любой тип данных в Angular и преобразовать в известный тип данных?

У меня есть служба ниже, получающая некоторые данные службы, и я хочу преобразовать ее в productDataClass с {productId: int; productName: string;}

По крайней мере, я хочу по крайней мере productId, которое является целым числом.

Отправка данных, аналогичных этому ресурсу,

https://jasonwatmore.com/post/2018/06/25/angular-6-communicating-between-components-with-observable-subject

public productDataClass: ProductDataClass;

this.productService.currentMessage.subscribe(currentMessage => {
  this.productDataClass = currentMessage

Затем я попробовал это, который не работает copyFromMessage типа any,

this.productService.currentMessage.subscribe(currentMessage => {
  this.copyFromMessage = currentMessage;
  this.productData = this.copyFromMessage.value;
  this.testString= this.productData.productName;

Ошибка:

Не удается прочитать свойство 'productName' изundefined

Базовая служба:

export class ProductService{

  private messageSource = new Subject();
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(currentMessage) {
    this.messageSource.next(currentMessage);
  }
}

Просмотр этого ресурса также: Ошибка наблюдаемого типа: невозможно прочитать свойство undefined

Снимок экрана с фактическими элементами:

CurrentMessage содержит фактические данные, следующие строки показывают неопределенные, enter image description here

['value'] по-прежнему выдает ошибку

enter image description here

Ответы [ 3 ]

1 голос
/ 08 ноября 2019

оформить заказ Ссылка на StackBlitz

Ваш productDataClass равен

export class Productdataclass {
       productId: number;
       productName: string;

     get _productId() {
         return this.productId;
     }
     set _productId(id:number){
        this.productId = id;
     }
    get _productName(){
        return this.productName;
    }
    set _productName(name: string){
       this.productName = name;
    }
} 
  • Ваш сервис

        import { Injectable } from '@angular/core';
        import { Subject } from 'rxjs';
    
        @Injectable()
        export class DataService {
               private messageSource = new Subject();
               currentMessage = this.messageSource.asObservable();
               constructor() { }
               changeMessage(currentMessage) {
                   this.messageSource.next(currentMessage);
               }
    
         }
    
  • В app.component.ts вы можете вызвать метод changeMessage () здесь при нажатии кнопки.

       export class AppComponent  {
    
            public productDataClass: Productdataclass =new Productdataclass();
            public copyFromMessage: Productdataclass = new Productdataclass();
            public testString : string;
    
            constructor(private data: DataService){ }
    
            ngOnInit(){
                 this.productDataClass._productId = 1 ;
                 this.productDataClass._productName='toothBrush';
                 this.data.currentMessage.subscribe(data =>{
                          console.log(data)
                          this.copyFromMessage = data['value'];
                          this.testString = this.copyFromMessage.productName;
                          console.log(this.testString);
                 })
           }
           call(){    
              this.data.changeMessage( {value:this.productDataClass} )
           }
      } 
    
0 голосов
/ 09 ноября 2019

Возникла проблема с расширением Visual Code Debugger Chrome. Можно использовать команду debugger между строками кодов, и значения отладчика будут отображаться правильно. Все остальные ответы в этом посте также действительны.

this.productService.currentMessage.subscribe(currentMessage => {
  this.copyFromMessage = currentMessage;
  debugger;
  this.productData = this.copyFromMessage.value;
  this.testString= this.productData.productName;

В этой строке кода расширение Chrome почему-то думает, что .this относится к подписке, а не к компоненту класса.

Вы можете использовать _this для доступа к компоненту класса.

0 голосов
/ 08 ноября 2019

Это ошибка времени выполнения JavaScript.

changeMessage() не вызывается с объектом этой структуры {value: {productName: ...}}

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