I\'m pretty new to java-/type-script and I\'ve some troubles grasping their concepts. I would like to call a method of another class. However, I\'ve been unsuccessful s
There are several problems with your code.
Taking this into account the fixed code would look like this:
export class Foo
{
calcSomeThing(parameter:number): number
{
//Stuff
}
}
class Bar
{
private foo:Foo = new Foo();
calcOtherThing(parameter: number): number
{
return this.foo.calcSomeThing(parameter)
}
}
I believe you need a constructor for classes in TypeScript. In the example I provide I made mine data holders, but it's not required. Additionally, your calculation functions need to return values. Also, in order to use Foo in an instance of Bar, you need to make an instance of Foo.
class Foo {
private data;
constructor(data: number) {
this.data = data;
}
calcSomeThing(parameter:number): number {
return parameter + 1;
}
}
class Bar {
private data;
private foo:Foo = new Foo(3);
constructor(data: number) {
this.data = data;
};
calcOtherThing(): number {
let result = this.foo.calcSomeThing(this.data);
return result;
}
}
let bar = new Bar(5);
console.log(bar.calcOtherThing()); // returns 6
It may not be right for all situations, but for the angular app I'm working on, I'm been using a service - here's what angular says about them. You can then call them like this:
smile.service.ts
export class SmileService {
addSmileMethod(input: string): string {
return input + ' :)';
}
}
smile-component.ts
import { SmileService } from './path/to/smile.service';
export class SmileComponent {
constructor(private smileService: SmileService) { }
ngOnInit() {
// Using the service
const smileString = this.smileService.addSmileMethod('Hello!');
console.log(smileString);
// Output is:
// Hello! :)
}
}
calcSomeThing
is a non-static method/function. Create an instance of Foo
to be able to call it:
let foo:Foo = new Foo();
let result:number = foo.calcSomeThing( parameter );
Never use var
in Typescript - let
is your friend.
Here's another example, but with a shared exported method.
a.ts
:
export function sharedMethod(a, b, c) { return a + b + c }
export default class A {
constructor(a, b, c) {
this.concat = sharedMethod(a,b,c);
};
}
And in b.ts
:
import { sharedMethod } from './a'
export default class B {
constructor(a, b, c) {
this.concat = sharedMethod(a,b,c)
};
}
and in c.ts
:
import './a'
import './b'
new A('hello', 'world', '!')
new B('hello', 'world', '!')