Angular 组件之间无法通信
我用的是Angular 6,我试着让它成为2个组件。第二个组件必须基于第一个组件的URL启动特定动画。我尝试使用“PreviousURL”解决方案,但它们并不总是有效,所以我想让这两个组件进行通信。在第一个组件中,有一个按钮是到达第二个组件的唯一方法。因此,当按下它时,它调用一个函数,该函数向声明当前URL的第二个组件发送消息。我寻找了一个合适的解决方案,并实施了它,但没有成功。第二个组件根本无法读取消息,我不知道为什么,因为我使用这个系统在我的项目中与另外两个组件进行通信。 这是第一个组件的代码: HTMLAngular 组件之间无法通信,angular,angular-services,angular-components,Angular,Angular Services,Angular Components,我用的是Angular 6,我试着让它成为2个组件。第二个组件必须基于第一个组件的URL启动特定动画。我尝试使用“PreviousURL”解决方案,但它们并不总是有效,所以我想让这两个组件进行通信。在第一个组件中,有一个按钮是到达第二个组件的唯一方法。因此,当按下它时,它调用一个函数,该函数向声明当前URL的第二个组件发送消息。我寻找了一个合适的解决方案,并实施了它,但没有成功。第二个组件根本无法读取消息,我不知道为什么,因为我使用这个系统在我的项目中与另外两个组件进行通信。 这是第一个组件的代
<ng-container *ngIf="api.availableAPI==true">
<div class="divider"></div>
<button type="button" (click)="send('test_message');" class="card-gray-button" [routerLink]=api.linkPlayground>TRY NOW</button>
</ng-container>
这是第二个组成部分:
Typescript
import { ResetService } from './../../../services/reset.service';
import { PreviousUrlService } from './../../../services/previous-url.service';
import { Component, OnInit, HostListener, Input} from '@angular/core';
import { ApiCard } from "../../model/ApiCard";
@Component({
selector: "api-card",
templateUrl: "./api-card.component.html",
styleUrls: ["./api-card.component.scss"]
})
export class ApiCardComponent implements OnInit {
@Input() api: ApiCard;
constructor(private resetService: ResetService) {}
ngOnInit() {}
// --> RIGHT HERE
send(message: string): void {
this.resetService.sendMessage(message);
console.log('function called');
}
}
import { Subscription } from 'rxjs';
import { Component, OnInit, Input, AfterViewChecked } from '@angular/core';
import { CATEGORIES } from './mock-category';
import { ActivatedRoute, Router, NavigationEnd, Params, NavigationStart } from '@angular/router';
import { until } from 'selenium-webdriver';
import { ResetService } from './../services/reset.service';
import elementIsSelected = until.elementIsSelected;
@Component({
selector: 'app-api-documentation',
templateUrl: './api-documentation.component.html',
styleUrls: ['./api-documentation.component.scss']
})
export class ApiDocumentationComponent implements OnInit, AfterViewChecked {
@Input() inputField: string;
myInnerHeight = 500;
categories = CATEGORIES;
private fragment: string;
private url: string;
baseUrl = 'https://external-api.intesasanpaolo.com/playground/';
apiTitle: string;
apiDescription: string;
landingBackgroundImage: string;
message: any;
subscription: Subscription;
constructor(private route: ActivatedRoute, private router: Router,
private resetService: ResetService) {
this.subscription = this.resetService.getMessage().subscribe(message => { this.message = message; });
}
ngOnInit() {
this.route.fragment.subscribe(fragment => {
this.fragment = fragment;
this.ngAfterViewInit();
});
this.route.data.subscribe(data => {
this.apiTitle = data.title;
this.apiDescription = data.description;
this.landingBackgroundImage = data.heroImage;
});
this.router.events.subscribe(val => {
if (val instanceof NavigationEnd) {
const patt = new RegExp('//api_documentation*/');
if (patt.test(val.url)) {
this.router.navigate(['/api_documentation']);
} else { this.router.navigate([val.url]); }
}
});
this.router.events.subscribe(event => {
if (event instanceof NavigationStart) {
this.previousUrl = event.url;
}
});
this.receive();
}
viewCategory(nameCategory: String) {
for (let i in this.categories) {
if (this.categories[i].name === nameCategory) {
if (this.categories[i].view) {
this.categories[i].view = false;
} else { this.categories[i].view = true; }
}
}
}
ngAfterViewInit(): void {
}
ngAfterViewChecked(): void {
autoscroll();
}
autoscroll(): void {
if (this.previousUrl === '/account-information') {
this.scrollToCategory('Account_Balance');
}
if (this.previousUrl === '/payments') {
this.scrollToCategory('sepa_instant_payment');
}
if (this.previousUrl === '/tools') {
this.scrollToCategory('iban_existance_verification');
}
}
// --> RIGHT HERE
receive(): void {
if (this.message != null) {
console.log('success: ' + this.message.text);
} else {
console.log('failure');
}
}
scrollToCategory(s: String) {
let htmlElement: HTMLElement = document.querySelector(
'#' + s
) as HTMLElement;
var posElemento: number = htmlElement.offsetTop;
posElemento -= 32;
try {
document.querySelector('#container-right').scrollTo({ left: 0, top: posElemento - 10, behavior: 'smooth' });
} catch (e) {
document.querySelector('#container-right').scrollTop = posElemento;
}
// (document.querySelector('#prova')).querySelector('#' + this.fragment).scrollIntoView();
}
}
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ResetService {
private subject = new Subject<any>();
sendMessage(message: string) {
this.subject.next({ text: message });
}
clearMessage() {
this.subject.next();
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
这就是我使用的服务:
Typescript
import { ResetService } from './../../../services/reset.service';
import { PreviousUrlService } from './../../../services/previous-url.service';
import { Component, OnInit, HostListener, Input} from '@angular/core';
import { ApiCard } from "../../model/ApiCard";
@Component({
selector: "api-card",
templateUrl: "./api-card.component.html",
styleUrls: ["./api-card.component.scss"]
})
export class ApiCardComponent implements OnInit {
@Input() api: ApiCard;
constructor(private resetService: ResetService) {}
ngOnInit() {}
// --> RIGHT HERE
send(message: string): void {
this.resetService.sendMessage(message);
console.log('function called');
}
}
import { Subscription } from 'rxjs';
import { Component, OnInit, Input, AfterViewChecked } from '@angular/core';
import { CATEGORIES } from './mock-category';
import { ActivatedRoute, Router, NavigationEnd, Params, NavigationStart } from '@angular/router';
import { until } from 'selenium-webdriver';
import { ResetService } from './../services/reset.service';
import elementIsSelected = until.elementIsSelected;
@Component({
selector: 'app-api-documentation',
templateUrl: './api-documentation.component.html',
styleUrls: ['./api-documentation.component.scss']
})
export class ApiDocumentationComponent implements OnInit, AfterViewChecked {
@Input() inputField: string;
myInnerHeight = 500;
categories = CATEGORIES;
private fragment: string;
private url: string;
baseUrl = 'https://external-api.intesasanpaolo.com/playground/';
apiTitle: string;
apiDescription: string;
landingBackgroundImage: string;
message: any;
subscription: Subscription;
constructor(private route: ActivatedRoute, private router: Router,
private resetService: ResetService) {
this.subscription = this.resetService.getMessage().subscribe(message => { this.message = message; });
}
ngOnInit() {
this.route.fragment.subscribe(fragment => {
this.fragment = fragment;
this.ngAfterViewInit();
});
this.route.data.subscribe(data => {
this.apiTitle = data.title;
this.apiDescription = data.description;
this.landingBackgroundImage = data.heroImage;
});
this.router.events.subscribe(val => {
if (val instanceof NavigationEnd) {
const patt = new RegExp('//api_documentation*/');
if (patt.test(val.url)) {
this.router.navigate(['/api_documentation']);
} else { this.router.navigate([val.url]); }
}
});
this.router.events.subscribe(event => {
if (event instanceof NavigationStart) {
this.previousUrl = event.url;
}
});
this.receive();
}
viewCategory(nameCategory: String) {
for (let i in this.categories) {
if (this.categories[i].name === nameCategory) {
if (this.categories[i].view) {
this.categories[i].view = false;
} else { this.categories[i].view = true; }
}
}
}
ngAfterViewInit(): void {
}
ngAfterViewChecked(): void {
autoscroll();
}
autoscroll(): void {
if (this.previousUrl === '/account-information') {
this.scrollToCategory('Account_Balance');
}
if (this.previousUrl === '/payments') {
this.scrollToCategory('sepa_instant_payment');
}
if (this.previousUrl === '/tools') {
this.scrollToCategory('iban_existance_verification');
}
}
// --> RIGHT HERE
receive(): void {
if (this.message != null) {
console.log('success: ' + this.message.text);
} else {
console.log('failure');
}
}
scrollToCategory(s: String) {
let htmlElement: HTMLElement = document.querySelector(
'#' + s
) as HTMLElement;
var posElemento: number = htmlElement.offsetTop;
posElemento -= 32;
try {
document.querySelector('#container-right').scrollTo({ left: 0, top: posElemento - 10, behavior: 'smooth' });
} catch (e) {
document.querySelector('#container-right').scrollTop = posElemento;
}
// (document.querySelector('#prova')).querySelector('#' + this.fragment).scrollIntoView();
}
}
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ResetService {
private subject = new Subject<any>();
sendMessage(message: string) {
this.subject.next({ text: message });
}
clearMessage() {
this.subject.next();
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
从'@angular/core'导入{Injectable};
从“rxjs”导入{observeable,Subject};
@注射的({
providedIn:'根'
})
导出类重置服务{
私有主体=新主体();
sendMessage(消息:字符串){
this.subject.next({text:message});
}
clearMessage(){
this.subject.next();
}
getMessage():可观察{
返回此.subject.asObservable();
}
}
如果你有什么建议,我很乐意听你的。谢谢 我认为在getMessage()的订阅中调用receive()时,使用事件发射器可能更简单。