首页 > 解决方案 > 你可以在 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
  });
});

谢谢你!

标签: angularprotractor

解决方案


是的,这是一个常规功能:

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
  });
});

推荐阅读