以角度2我想通過服務在兩個單獨的組件之間進行通信,但它們不是子級和父級。 服務組件:兩個單獨的組件角之間的通信2
import { Injectable, Inject } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class SignUpService {
private openDialog = new Subject<any>();
openDialogObservable$ = this.openDialog.asObservable();
constructor(){}
public open(data: any) {
if (data) {
this.openDialog.next(data);
}
}
}
SignUpComponent:
import { Component, OnInit, Input, ViewChild } from '@angular/core';
import {SignUpService} from "../services/signup-service.service";
import { Subscription } from 'rxjs';
@Component({
selector: 'signup',
templateUrl: './signup.html',
})
export class SignUpComponent implements OnInit {
private SignUpSubscription: Subscription;
display:boolean = false;
constructor(private signUpService: SignUpService) {
}
ngOnInit() {
this.SignUpSubscription =
this.signUpService.openDialogObservable$.subscribe((res) => {
if (res == 'show') {
this.display = true;
}
});
}
showDialog() {
this.display = true;
}
hideDialog() {
this.display = false;
}
}
註冊HTML:
<div style="background-color: #4cae4c; width: 1000px" class="ui-rtl"
dir="rtl">
<p-dialog [(visible)]="display" width="200px" modal="true"
[responsive]="true" tabindex="-1" role="dialog" aria-
labelledby="mySmallModalLabel" aria-hidden="true" >
<p-header class="text-center">
SignUp
</p-header>
<form (ngSubmit)="onSubmit($event)" #signUpForm="ngForm">
<div class="group signup form-group" style="width:300px">
<input #firstName="ngModel" class="form-control"
[(ngModel)]="createuser.firstName" name="firstname" type="text" pattern="[\u0600-\u065F\u066A-\u06EF\u06FA-\u06FF][\u0600-\u065F\u066A-\u06EF\u06FA-\u06FF]+" required>
<span class="highlight"></span>
<span class="bar"></span>
<label>Name</label>
</div>
</form>
</p-dialog>
關於這個網站應該說我已經有模態primeng庫取得它,它採用了特殊的標籤。 在標題組件中,我有一個按鈕(註冊)註冊組件和模板和服務在一個單獨的文件夾中。我想當用戶點擊該按鈕時,一個模式框將打開。 頭組件:
import {Component, OnInit, EventEmitter, Output, Input, ViewChild} from '@angular/core';
import {SignUpService} from "../services/signup-service.service";
import {Subscription} from 'rxjs';
@Component({
selector: 'header-component',
templateUrl: './header.component.html',
})
export class HeaderComponent {
private subscription: Subscription;
constructor(private signUpService: SignUpService
) {
}
showDialog() {
this.signUpService.open('show');
}
,最後這頭HTML:
<a type="button" (click)="showDialog()" >Sign Up</a>
問題:當我在標題點擊註冊按鈕的模式對話框不會打開。 沒有錯誤,但是當我在源代碼中插入斷點時,它不會去signup.component.ts。問題是什麼?我該如何解決它? 感謝您以簡單的方式提供幫助。 也有這兩個鏈接,類似於我的代碼。 Parent and children communicate via a service和 Example of Component Communication in Angular 2/4
感謝,但沒有奏效
然後訂閱該事件。 –