首页 > 解决方案 > 角度中的类或函数实用程序

问题描述

您如何以及何时在 angular2 中创建实用程序/帮助程序类或函数?

我创建了一个文件夹helpers,用于存放将要创建的所有通用函数和类。

但现在我有这段代码将用于 8 个组件。

/**
   * this is initialize after the elements have been loaded. called inside ngAfterViewInit methods
   * this sets up the joyrideService
   */
  joyRideInit(): void {
    const fileNameNotes = this.designNotes.map((matchImgUrl) =>
      extractKeyFromFilename(matchImgUrl)
    );

    const seenNotes = {
      viewed_notes: {
        match: fileNameNotes,
        ...this.viewedNotes
      }
    };

    this.joyrideService
      .startTour({
        steps: [
          'matchFirst',
          ...this.designNotes,
          'guidedTourBtn',
          'saveNextBtn'
        ]
      })
      .subscribe(null, null, () => {
        this.updateUserNotes(seenNotes);
      });
  }

  /**
   * sends a resquest to update the notes
   * @param userUpdateNotes 
   */
  updateUserNotes(userUpdateNotes): void {
    this.userService
      .updateUser(userUpdateNotes, this.user.id)
      .pipe(
        first(),
        map((result) => {
          // * result no used.
          console.log('res', result);
        }),
        catchError((error) => {
          console.error('display-notes#nextNoteOrClose: error in ', error);
          throw error;
        })
      )
      .subscribe();
  }

我应该把它作为一个类或函数吗?这将有 4 个参数来自将使用它的组件。

标签: angulartypescript

解决方案


创建共享/公共服务,所有像这样的方法你都可以把它放在那里进行默认注入。


推荐阅读