以角度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
感谢,但没有奏效
然后订阅该事件。 –