我正在使用Angular 6,并且试图使两个组件通信。第二个组件必须根据第一个组件的URL开始特定的动画。我尝试使用“以前的URL”解决方案,但它们并不总是有效,因此我想进行两个组件的通信。在第一个组件中,有一个按钮是到达第二个组件的唯一方法。因此,当按下它时,它将调用一个函数,该函数向第二个组件发送一条消息,以声明当前URL。我一直在寻找合适的解决方案,但没有成功实施。第二个组件根本无法读取消息,我也不知道为什么,因为我使用此系统进行项目中另外两个组件的通信。 这是第一个组件的代码:
HTML
<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>
打字稿
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();
}
}
如果您有任何建议,我们将很高兴收到您的来信。谢谢!