Typescript: Calling a “method” of another class

后端 未结 5 2057
故里飘歌
故里飘歌 2021-02-13 11:51

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

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-13 12:19

    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! :)
      }
    
    }
    

提交回复
热议问题