Tim Mitchell
Tim Mitchell

Reputation: 653

Can you create a function in an Angular ts file?

I'm pretty new to Angular and typescript (ts) files.

Is there a way to create a function in a ts file so as to not have to write duplicate code?

For example,

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

Thank You!

Upvotes: 1

Views: 92

Answers (1)

julianobrasil
julianobrasil

Reputation: 9377

Yeah, it's a regular function:

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

Upvotes: 1

Related Questions