2016-12-03 16 views
2

我有一個基礎構件是這樣的:訂閱在服務意外取消(從擴展路由組件)

@Component({}) 
export class PageComponent implements OnInit, OnDestroy { 
    title: string; 

    constructor(
    /* other stuff */ 
    protected uiService: UIService) { } 

    ngOnInit() { 
    this.uiService.set('title', this.title); 
    this.uiService.set('something', false); 
    } 

    ngOnDestroy() { 
    /* cleanup */ 
    } 
} 

和擴展它幾個路由組件,例如:

@ExtendedComponent({ templateUrl: './page-one.component.html' }) 
export class PageOneComponent extends PageComponent { 
    title: string = 'Page One Title'; 
} 

@ExtendedComponent({ templateUrl: './page-two.component.html' }) 
export class PageTwoComponent extends PageComponent { 
    title: string = 'Page Two Title'; 

    ngOnInit() { 
    super.ngOnInit(); 
    /* do stuff specific to PageTwoComponent */ 
    this.uiService.set('something', true); 
    } 
} 

@ExtendedComponent裝飾器這個:

export function ExtendedComponent(annotation: any) { 
    return (target: Function) => { 
    const parentTarget = Object.getPrototypeOf(target.prototype).constructor; 

    const parentAnnotations = Reflect.getMetadata('annotations', parentTarget); 
    const metadata = new Component({ ...parentAnnotations[0], ...annotation}); 
    Reflect.defineMetadata('annotations', [metadata], target); 

    const parentParamTypes = Reflect.getMetadata('design:paramtypes', parentTarget); 
    const parentParameters = Reflect.getMetadata('parameters', parentTarget); 
    Reflect.defineMetadata('design:paramtypes', parentParamTypes, target); 
    Reflect.defineMetadata('parentParameters', parentParameters, target); 
    }; 
} 

我遇到的問題是UIService

@Injectable() 
export class UIService { 
    private buffer: any = {}; 
    private dispatcher: Subject<any> = new Subject(); 

    constructor() { 
    this.dispatcher 
     .map(state => this.buffer = { ...this.buffer, ...state }) 
     .debounceTime(50) 
     .do(() => { /* does something */}) 
     .subscribe(); 
    } 

    set(key: string, value: any) { 
    console.log(this.dispatcher.observers); // <-- [MapSubscriber] when working 
              // <-- [] when not working 
    this.dispatcher.next({ [key]: value }); 
    } 
} 

當我與其他組件的頁面(這裏沒有顯示)之間進行導航,一切工作正常。但是,當我從PageOneComponentPageTwoComponent(均擴展PageComponent),調度程序在UIService中的主題停止工作(console.log在set方法中顯示一個空數組後幾個調用)。

我不知道爲什麼會發生這種情況或者是什麼原因造成的。有任何想法嗎?

+0

您不會將任何函數傳遞給subscribe()方法。所以我猜訂閱已被垃圾收集器刪除 – Rem

+0

@Rem認爲你是對的,我把'()=> {/ *做了一些* /}'從'do()'移動到'subscribe()',工程..謝謝!如果你可以添加一個答案,我會接受(; – Sasxa

回答

1

您不會將任何函數傳遞給subscribe()方法。因此訂閱被垃圾收集器刪除