首页 文章

父路由组件无法缓存子路由组件中的Angular 5 Subject Observer

提问于
浏览
0

所以我正在使用angular 5 ,,,使用这样的子路径:

const routes: Routes = [
  {
    path: 'inbox', component: InboxComponent,
    children: [
      { path: ':id', component: RequestDetailsComponent }
    ]
  },

  { path: '', redirectTo: '/inbox', pathMatch: 'full' },
  { path: '**', component: InboxComponent }

];

基本上我想改变收件箱组件中的内容如果我加载了'inbox / id'...所以我希望收件箱组件做一些动作,当我点击详细信息组件上的按钮时,我想要更改父路由.lets假定更改是一个html类添加 - 删除..

我用Subject来观察变化,通过创建服务,收件箱服务,如下:

mport { Injectable } from "@angular/core";
import { ApiHelperService } from "../../shared/services/api-helper.service";
import { Subject } from "rxjs/Subject";
import { Question } from "../../models/question";

@Injectable()
export class InboxService {
    uri = 'questions?order=desc&sort=activity&site=stackoverflow&filter=!-*f(6rLIPlIq';
    colors = ['bg-primary-400', 'bg-purple-400', 'bg-info-400', 'bg-warning-400', 'bg-danger-400', 'bg-violet-400', 'bg-success-400'];
    public  openRequestDetails = new Subject<number>();

    changeView(view: number){
        this.openRequestDetails.next(view);
    }
}

在我的RequestDetailsComponent中,我在服务中调用更改视图函数,如下所示:

onChangeView() {
    this.inboxService.changeView(this.mode);
  }

在我的InboxCompnent中,我订阅了这样的主题:

@Component({
  selector: 'app-inbox',
  templateUrl: './inbox.component.html',
  styleUrls: ['./inbox.component.scss'],
  providers: [InboxService]
})
export class InboxComponent implements OnInit, OnDestroy {

  private subscription: Subscription;
 ngOnInit() {
        this.subscription = this.inboxService.openRequestDetails
          .subscribe(
          (request: any) => {
            console.log(request);
          },
          (error: any) => console.log('error'),
          () => console.log('complete')
        )
}

作为参考,这里是我的app.module ,,我删除了无关的导入:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';


import { AppComponent } from './app.component';
import { InboxComponent } from './inbox/inbox.component';
import { RequestComponent } from './inbox/request/request.component';
import { RequestDetailsComponent } from './inbox/request-details/request-details.component';
import { InboxService } from './inbox/inbox.service';
import { AppRoutingModule } from './routing/app-routing.module';
import { RouterModule } from '@angular/router';

@NgModule({
  declarations: [
    AppComponent,
    InboxComponent,
    RequestComponent,
    RequestDetailsComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    AppRoutingModule
  ],
  providers: [ApiHelperService, InboxService],
  bootstrap: [AppComponent]
})
export class AppModule { }

At the end,this subscription never fires when I am at the child route inbox/123...

任何的想法???我不能使用子组件,它必须是子路由..因为我将有许多子路由 .

如果我在相同的组件RequestDetailsComponent中添加了订阅..它工作正常..

1 回答

  • 0

    我遇到了类似的问题,问题的根源在于服务的DI . 您是否在包含所有这些组件的共享模块中注入 InboxService ?检查模块的 providers 数组 - 您尚未在此处共享它 .

相关问题