angular - How to call a method from another component in Angular?
问题描述
I'm trying to call a mehtod from one Angular component to another
This is one.component.ts
, it has to check if it's a day off
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;
} }
and another.component.ts
; if day off = true, it doesn't show todos for that day:
filterDateInDisabledArea(): boolean {
for (const disabledArea of this.disabledAreas) {
if (isDayOfWeekDisabled()) {
return false;
}
}
return true;
}
but I can't understand how to create a connection between these components.
解决方案
It depends, if you are calling from sibling to sibling then you would abstract the method to a service that both will use:
Service
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);
}
}
component
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);
});
}
});
}
}
推荐阅读
- python - 如何将带有 in 子句的数据库查询转换为 SQLAlchemy 中的列表列表
- android - 更改图像,如何重新加载媒体存储?
- r - sf:将几何中的纬度/经度写入单独的列并保留 ID 列
- android - AppNotIdleException 由于 AnimatedVectorDrawableCompat
- javascript - CLUEDO CHALLENGE:使用函数内部的函数来检索数组中对象的随机键
- vb.net - 有没有办法将给定的属性标识符作为 VB 中的参数传递给 Sub?
- r - 使用 mutate() dplyr 计算平均值时出错
- outlook - 具有相同邮件地址的 Outllok 邮件帐户
- dask - 附加来自另一个数据帧的行
- reactjs - 如何从现有的 webform iis 托管应用程序链接到 react asp mvc 应用程序?