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

时间:2017-11-20 15:36:25

标签: angular routing observable

所以我正在使用这样的子路线来处理角度5 ,,,

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

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

];

基本上我想更改收件箱组件中的内容如果我加载了路径' inbox / id' ...所以我希望收件箱组件执行某些操作,当我点击按钮时在详细信息组件上,我想更改父路由..小组假设更改是一个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 { }

最后,当我在子路径收件箱/ 123时,此订阅永远不会触发......

任何想法???而且我不能使用儿童成分,它必须是儿童路线..因为我将有许多儿童路线。

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

1 个答案:

答案 0 :(得分:0)

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