Angular2 Observable在数据更改之前不会呈现

时间:2016-10-12 10:59:18

标签: angular angular2-routing angular2-services

我是Angular2的新手,所以希望我有一个容易解决的问题:)

我正在尝试使用可观察服务跨多个视图(这是单独的路径)共享数据(按服务本地存储在内存中的对象列表)。问题是,当我改变路线(即通过链接)时,共享数据不会呈现,直到我"添加"列表中的新项目(即当前路线)。我已经看到很多关于堆栈溢出的类似的问题,但没有一个解决方案有效。

我不知道错误是在我的路由中,我的ngInit函数(即在数据完成之前呈现?)还是我自己定义服务/组件的方式。以下是一些代码片段来说明:

路由:

const appRoutes: Routes = [
  {
    path: '',
    redirectTo: '/running-order',
    pathMatch: 'full'
  },
  {
    path: 'running-order',
    component: RunningOrderComponent
  },
  {
    path: 'enquiry',
    component: EnquiryComponent
  },
  {
    path: 'config',
    component: ConfigComponent
  }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

服务

@Injectable()
export class ChaptersService{

    //Observable Source
    private chaptersSource:Subject<BaseChapter[]>;

    //Observable Stream
    chapters$: Observable<BaseChapter[]>;

    //DataStore
    private dataStore:{ chapters: BaseChapter[] };

    constructor() {
        console.log('chapter service instantiated');
        this.chaptersSource = new Subject<BaseChapter[]>();
        this.chapters$ = this.chaptersSource.asObservable();
        this.dataStore = { chapters: [] };      
    }

    loadAll() {
        this.chaptersSource.next(this.dataStore.chapters);
    }

    addChapter(data:BaseChapter){
        this.dataStore.chapters.push(data);
        this.chaptersSource.next(this.dataStore.chapters);
    }
}   

组件(路由):

@Component({
    selector: 'myenquiry',
    templateUrl: 'enquiry.component.html',
    styleUrls: ['enquiry.component.css']
})

export class EnquiryComponent implements OnInit{
    config : Config;
    title = 'Enquiry Angular App';
    selectedChapter: BaseChapter;

    chapters$: Observable<BaseChapter[]>;

    constructor(private chaptersService:ChaptersService){}

    ngOnInit():void {
        this.chaptersService.loadAll();
        this.chapters$ = this.chaptersService.chapters$;
        console.log('enquiry component initialised...');
    }

    onSelect(chapter: BaseChapter): void {
      this.selectedChapter = chapter;
    }

    addChapter():void {
        var chapter:Chapter = new Chapter(0);
        chapter.initChapter("untitled",4);
        this.chaptersService.addChapter(chapter);
        this.selectedChapter = chapter;
    }
}

组件模板:

<h2>List of Chapters</h2>
<ul class="chapters">
    <li *ngFor="let chapter of chapters$ | async" [class.selected]="chapter === selectedChapter" (click)="onSelect(chapter)" >
        <span class="idStyle">{{chapter.id}}</span> {{chapter.name}}
    </li>
</ul>
<chapter [chapterData]="selectedChapter"></chapter>
<button (click)="addChapter()">Add Chapter</button>

谢谢,菲尔。

1 个答案:

答案 0 :(得分:2)

更改

private chaptersSource:Subject<BaseChapter[]>; 

private chaptersSource:ReplaySubject<BaseChapter[]>;

这样,如果observable在你的组件绑定之前得到一个值,那么它将被推送到最后一个值。