angular.service vs angular.factory

后端 未结 9 2332
走了就别回头了
走了就别回头了 2020-11-22 02:50

I have seen both angular.factory() and angular.service() used to declare services; however, I cannot find angular.service anywhere in official documentation.

9条回答
  •  天命终不由人
    2020-11-22 02:58

    Simply put ..

    const user = {
      firstName: 'john'
    };
    
    // Factory
    const addLastNameFactory = (user, lastName) => ({
      ...user,
      lastName,
    });
    
    console.log(addLastNameFactory(user, 'doe'));
    
    // Service
    const addLastNameService = (user, lastName) => {
      user.lastName = lastName; // BAD! Mutation
      return user;
    };
    
    console.log(addLastNameService(user, 'doe'));

提交回复
热议问题