angular - 你可以在 Angular ts 文件中创建一个函数吗?
问题描述
我对 Angular 和 typescript (ts) 文件很陌生。
有没有办法在 ts 文件中创建函数以便不必编写重复的代码?
例如,
describe('Navigating to My Page', () => {
beforeAll(done => {
myPage = new MyPage();
myPage.navigate().then(() => {
done();
});
it('user can update stuff', done => {
//Blah blah blah
});
});
describe('Navigating to Another Page', () => {
beforeAll(done => {
anotherPage = new AnotherPage();
anotherPage.navigate().then(() => {
done();
});
});
//Now, I want to navigate back to My Page. Is there a way to do this without writing the exact same code over again?
describe('Navigating to My Page', () => {
beforeAll(done => {
myPage = new MyPage();
myPage.navigate().then(() => {
done();
});
it('user can update stuff', done => {
//Blah blah blah
});
});
谢谢你!
解决方案
是的,这是一个常规功能:
function navigateToPage<T = any>(page: T, done: () => void) {
page.navigate().then(() => done());
}
describe('Navigating to My Page', () => {
beforeAll(done => {
myPage = new MyPage();
navigateToPage<MyPage>(myPage,done);
});
it('user can update stuff', done => {
//Blah blah blah
});
});
describe('Navigating to Another Page', () => {
beforeAll(done => {
anotherPage = new AnotherPage();
navigateToPage<AnotherPage>(anotherPage,done);
});
});
describe('Navigating to My Page', () => {
beforeAll(done => {
myPage = new MyPage();
navigateToPage<MyPage>(myPage,done);
});
it('user can update stuff', done => {
//Blah blah blah
});
});
推荐阅读
- ssl - 在具有 TLS 的服务器中仅启用 secp384r1 时,0-RTT 不起作用。为什么?
- vue.js - 尝试不显示 v-model 更改,直到我想显示它
- excel - 如何从excel中两个日期之间的日期列表中省略周末日期
- c++ - 将 2 个 32 位整数相乘而不会溢出
- java - 无法为 Android 应用程序初始化应用程序检查
- amazon-web-services - AWS Lambda/Secrets Manager 权限不再起作用 (Pulumi)
- swift - 我正在尝试从 Swift 5 输入格式化的日期字符串为“yyyy-mm-dd H:i:s +0000”mySQL。相反,我得到“yyyy-mm-dd H:i:s 0000”。如何添加“+”?
- tensorflow - 如何正确测试张量流模型的运行时间
- python - 如果来自 Python 字典的子类,则 LRU 缓存不可散列的类型
- python - 如何根据python中特定列中的值将数据集划分为多个数据集?