我正在尝试从一个Angular组件调用另一个方法
这是one.component.ts
,它必须检查是否有一天休息
export class CalendarComponent implements OnInit {
isDayOfWeekDisabled(dayOfWeek: number): boolean {
let dateIsDisabled = false;
const workDay=
moment(this.viewDate).startOf('isoWeek').add(dayOfWeek, 'd');
this.disabledAreas.forEach((item) => {
if (item.start.isSame(moment(workDay)) &&
item.end.isSame(moment(workDay.endOf('day')))) {
dateIsDisabled = true;
}
});
return dateIsDisabled;
} }
和another.component.ts
;如果day off = true,则不会显示当天的待办事项:
filterDateInDisabledArea(): boolean {
for (const disabledArea of this.disabledAreas) {
if (isDayOfWeekDisabled()) {
return false;
}
}
return true;
}
但是我不明白如何在这些组件之间建立连接。
答案 0 :(得分:1)
这取决于,如果您要从同级调用到同级,则需要将该方法抽象为两种都将使用的服务:
服务
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MruanovaService {
private subject = null;
data$ = null;
constructor(private httpClient: HttpClient) {
this.init();
}
init() {
this.subject = new BehaviorSubject<any>({});
this.data$ = this.subject.asObservable();
}
getProjects(): void {
const url = 'https://246gg84zg8.execute-api.us-west- 2.amazonaws.com/prod/projects/';
const headers = new HttpHeaders({ 'Content-Type': 'text/plain; charset=utf-8' });
const options = { headers: headers };
const value = this.httpClient.get(url, options); // HTTP GET
this.subject.next(value);
}
}
组件
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { MruanovaService } from 'src/app/services/Mruanova.service';
@Component({
selector: 'app-mruanova',
templateUrl: './mruanova.component.html',
styleUrls: ['./mruanova.component.scss']
})
export class MruanovaComponent implements OnInit {
projects = null;
constructor(public MruanovaService: MruanovaService) {}
ngOnInit() {
this.MruanovaService.getProjects();
this.MruanovaService.data$.subscribe(res => {
if (res.subscribe) {
res.subscribe(response => {
this.projects = response.Items.sort(function (a, b) {
return parseFloat(a.ID) - parseFloat(b.ID);
});
}, r => {
console.log('ERROR', r);
});
}
});
}
}