2017-02-08 14 views
0

У меня есть проблема при использовании предметов в угловой 2. Я получаю следующее сообщение об ошибке при запуске приложения:Углового вопрос 2 типирование при использовании предмета

Type '{}' is not assignable to type 'UserDevice[]'.)

  • У меня есть компонент с список userDevices.
  • И сервис, предоставляющий пользовательские устройства.

// Служба

export class UserDeviceLocalService { 

    udSubject = new ReplaySubject(); 
    tmpUserDevices: UserDevice[] = []; 

    constructor() { 
    } 

    createUserDevices(userDevice){ 
    this.tmpUserDevices.push(userDevice); 

    // localStorage.setItem('userdevices', JSON.stringify(this.tmpUserDevices)); 
    this.udSubject.next(this.tmpUserDevices); 
    } 
} 

// компонент

export class UserDeviceMenuComponent implements OnInit { 

userDevices: UserDevice[]; 

constructor(private userDeviceLocalService: UserDeviceLocalService) { 
} 

ngOnInit() { 
    this.userDeviceLocalService.udSubject.subscribe(userDevices => this.userDevices = userDevices); 
} 

ответ

1
createUserDevices(userDevice){ 
    this.tmpUserDevices.push(userDevice); 
    this.udSubject.next(this.tmpUserDevices); 
    } 

также:

export class UserDeviceLocalService { 
    udSubject = new ReplaySubject<UserDevice[]>(); 
    ... 
} 

и убедитесь, что вы отписать наблюдаемым, когда компонент уничтожен, чтобы избежать утечки памяти.

export class UserDeviceMenuComponent implements OnInit { 

userDevices: UserDevice[]; 
supscription: Subscription; 

constructor(private userDeviceLocalService: UserDeviceLocalService) { 
} 

ngOnInit() { 
    this.subscription = this.userDeviceLocalService.udSubject.subscribe(userDevices => this.userDevices = userDevices); 
} 

ngOnDestroy() { 
this.subscription.unsubscribe(); 
} 

Или используйте async трубу, которая обрабатывает отписку для вас.

1

может быть, эта линия нужно изменить

this.udSubject.next(userDevice); 

в

this.udSubject.next(tmpUserDevices); 

потому что userDevice является объектом, а не массив объектов

+0

Да, вы правы. Я сделал это только для тестирования. Я редактировал мой код, все еще получая ошибку – RSSD

0

Вы должны указать тип при объявлении/инстанцирования вашего Subject поля:

udSubject = new ReplaySubject<UserDevice[]>(); 

В вашем примере, что вы, вероятно, нужно new ReplaySubject<UserDevice[]>(1); так только последнее значение будет проиграно.

В таком случае вы можете также использовать BehaviorSubject вместо ReplaySubject и устранить tmpUserDevices:

export class UserDeviceLocalService { 

    udSubject = new BehaviorSubject<UserDevice[]>([]); 

    createUserDevices(userDevice: UserDevice) { 
     let devices = this.udSubject.value; 

     // maybe clone array first? 
     devices = devices.slice(); 

     devices.push(userDevice); 

     // localStorage.setItem('userdevices', JSON.stringify(devices)); 
     this.udSubject.next(devices); 
    } 
} 

И не забудьте подписаться не-подписки (ы) на ngOnDestroy().

В этой статье описаны некоторые аспекты системы типа машинопись:

http://blog.angular-university.io/typescript-2-type-system-how-does-it-really-work-when-are-two-types-compatible-its-actually-quite-different-than-other-type-systems/