Вызов метода компонента из службы завершается неудачно из-за нулевой ошибки - PullRequest
0 голосов
/ 18 февраля 2020

Я пытаюсь вызвать диалоговое окно из моей службы аутентификации. Я в основном пытаюсь вызвать его, как только пользователь аутентифицирован. Я создал компонент диалога под названием shared-modal.component. Этот компонент внедряется в компонент соглашения html. Компонент соглашения предоставляет метод загрузки, который будет пытаться открыть общий модал.

В настоящий момент я получаю экземпляр соглашения с дочерним представлением представления null в сервисе и, следовательно, не могу вызвать. Может кто-нибудь сказать мне, как еще я могу вызвать диалоговое окно

Поделиться модальный компонент

import { Component, Input} from '@angular/core';
declare var $: any;
@Component({
    selector: 'shared-modal',
    templateUrl: './shared-modal.component.html'
})
export class SharedModalComponent {
    _isopen = false;
    private _modalSize = 1; // 1:normal, 2: medium, 3: large, 4: extra large
    public get modalSize() {
        return this._modalSize;
    }

    @Input()
    public set modalSize(value) {
        this._modalSize = value;
    }

    get open(): boolean {
        return this._isopen;
    }

    @Input()
    set open(val: boolean) {
        this._isopen = val;
    }
    getModalDialogClass() {
        if (this.modalSize == null || this.modalSize <= 1 || this.modalSize > 4) {
            return 'modal-dialog modal-sm';
        } else if (this.modalSize <= 2) {
            return 'modal-dialog modal-md';
        } else if (this.modalSize <= 3) {
            return 'modal-dialog modal-lg';
        }  else if (this.modalSize <= 4) {
            return 'modal-dialog modal-xl';
        }
    }
}

Общий модальный html

<div id="modal_container">
        <div id="shared_modal" class="modal fade show" data-backdrop="static" data-keyboard="false" role="dialog" [ngStyle]="{'display': _isopen ? 'block' : 'none','z-index':'1050' }">
            <div [ngClass] = "getModalDialogClass()">
                <div class="modal-content">
                    <div class="modal-header">
                        <ng-content select=[header]></ng-content>
                    </div>
                    <div class="modal-body">
                        <ng-content select=[body]></ng-content>
                    </div>
                    <div class="modal-footer">
                        <ng-content select=[footer]></ng-content>
                    </div>

                </div>
            </div>
        </div>
        <div class="modal-backdrop fade show" *ngIf="_isopen" style="display: block; z-index: 1040;"></div>
        <div class="modal-backdrop fade show" *ngIf="!_isopen" style="display: none; z-index: 1040;"></div>
    </div>

Соглашение html

<shared-modal [modalSize]="4" [open]="agreementWindowOpened">
    <div style="width: 100%;" header>
        <div style="text-align: right">
            <div class="etp-close pull-right" (click)="dismissAgreementWindow()"></div>
        </div>
        <h4 class="modal-title">Agreement</h4>
    </div>
    <div body>
                Hello World

    </div>
    <div footer>
    </div>
</shared-modal>

Компонент соглашения

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

@Component({
  selector: 'app-agreement',
  templateUrl: './agreement.component.html',
  styleUrls: ['./agreement.component.scss']
})
export class AgreementComponent implements OnInit {

  agreementWindowOpened: boolean;

  constructor() { }

  ngOnInit() {
  }


 Load() {
    this.agreementWindowOpened = true;
  }

  dismissAgreementWindow() {
    this.agreementWindowOpened = false;
}
}

Сервис

@ViewChild(AgreementComponent, { static: false }) agreement: AgreementComponent;

    authCallback = (errorDesc: any, token: any, error: any, tokenType: any) => {

    if (this.userTryingToResetPassword(token, errorDesc)) {

      const passResetApplication = this.createUserAgentApplication(this.passwordResetAuthority);
      passResetApplication.loginRedirect(this.settings.aad.b2cScopes);
    }
    if (!errorDesc) {
      this.cacheUserPermissions();
      // Call the agreement dialog box here
      if (this.agreement) {
       this.agreement.Load();
      }
    }

  }

1 Ответ

0 голосов
/ 19 февраля 2020

@ ViewChild предназначен только для работы с компонентами и директивами, поэтому возвращает ноль. Что вам, вероятно, нужно, это динамически создавать модальный компонент. В официальных документах есть довольно хороший урок о том, как это сделать https://angular.io/guide/dynamic-component-loader

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