Круговая зависимость между компонентами в угловых - PullRequest
0 голосов
/ 03 мая 2019

Я получаю циклическую зависимость, так как я использую компоненты в другом, у меня есть четыре различных компонента следующим образом:

  1. MasterListComponent.ts
  2. MasterDetailComponent.ts
  3. ChildListComponent.ts
  4. ChildDetailComponent.ts

В MasterListComponents я использую MasterDetailComponent.ts в качестве всплывающего окна модели следующим образом

import { BsModalService, ModalDirective } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap';
import { MasterDetailComponent } from '../master-detail/master-detail.component';

@Component({
  selector: 'master-list',
  templateUrl: './master-list.component.html',
  providers: [MasterDetailComponent , BsModalRef],
})
export class MasterListComponent implements OnInit {

constructor(private modalService: BsModalService) {

  }

showMasterChildComponent() {
setTimeout(() => {this.bsModalRef = this.modalService.show(MasterDetailComponent, {
      initialState: {
        itemList: data['data'
      },
      class: 'modal-lg'
    })}, 1000); 
  }
}

тот же компонент masterdetail используется вChildDetailCompnent выглядит следующим образом

import { MasterListComponent } from './master-list/master-list.component';
@Component({
  selector: 'child-detail-view',
  templateUrl: './child-detail.component.html',
  providers: [MasterListComponent],
})
export class ChildDetailComponent implements OnInit {
constructor(
    public bsModalRef: BsModalRef,
    private modalService: BsModalService,
    private e_handlet: MasterListComponent) {
  }

showMasterDetailComponent() {
    this.e_handlet.showMasterChildComponent(eventId);
  }

}

Теперь я хочу вызвать компонент ChildDetail в MasterDetailComponent и получить циклическую ошибку зависимости.

Как решить эту проблему?

1 Ответ

0 голосов
/ 03 мая 2019

Позвольте мне показать пример модального диалога подтверждения

ПРОВЕРКА РАБОЧИЙ СТЕКБЛИЦ

Я использую сервис для обмена данными из модального с родительским компонентом

Ваш app.module.ts что-то вроде: ~

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ModalModule } from 'ngx-bootstrap/modal';
import { MessageService } from './message.service';
import { ConfirmDialogComponent } from './confirm-dialog/confirm-dialog.component';

@NgModule({
  declarations: [
    AppComponent,
    ConfirmDialogComponent,
  ],
  imports: [
    BrowserModule,
    ModalModule.forRoot(),
  ],
  providers: [
    MessageService,
  ],
  bootstrap: [AppComponent],
  entryComponents: [
    ConfirmDialogComponent,
  ]
})
export class AppModule { }

service.ts может выглядеть примерно так: ~

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal';

import { ConfirmDialogComponent } from './confirm-dialog/confirm-dialog.component';

@Injectable()
export class MessageService {
  bsModalRef: BsModalRef;

  constructor(
    private bsModalService: BsModalService,
  ) { }

  confirm(title: string, message: string, options: string[]): Observable<string> {
    const initialState = {
      title: title,
      message: message,
      options: options,
      answer: "",
    };
    this.bsModalRef = this.bsModalService.show(ConfirmDialogComponent, { initialState });

    return new Observable<string>(this.getConfirmSubscriber());
  }

  private getConfirmSubscriber() {
    return (observer) => {
      const subscription = this.bsModalService.onHidden.subscribe((reason: string) => {
        observer.next(this.bsModalRef.content.answer);
        observer.complete();
      });

      return {
        unsubscribe() {
          subscription.unsubscribe();
        }
      };
    }
  }

}

confirm-dialog.component что-то вроде ниже: ~

export class ConfirmDialogComponent {
    title: string;
    message: string;
    options: string[];
    answer: string = "";

    constructor(
        public bsModalRef: BsModalRef,
    ) { }

    respond(answer: string) {
        this.answer = answer;
        this.bsModalRef.hide();
    }
}

parent.component.ts примерно так: ~

import { Component } from '@angular/core';

import { MessageService } from './message.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  answers: string[] = [];

  constructor(
    private messageService: MessageService,
  ) {
  }

  confirm() {
    this.messageService.confirm(
      "Confirmation dialog box",
      "Are you sure you want to proceed?",
      ["Yes", "No"])
      .subscribe((answer) => {
        this.answers.push(answer);
      });
  }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...