Angular随记:创建一个服务

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

目录

一、创建服务  

二、服务使用

1.引入服务

2.配置服务

3.使用服务

未完待续。。。


一、创建服务  

ng g service [name]          

Creates a new, generic service definition in the given or default project. 

在项目services目录下,创建一个myservice服务,命令如下:

ng generate service services/myservice

或 简写

ng g service services/myservice

创建成功后,目录中多了myservice.service.ts、myservice.service.spec.ts两个文件。

在myservice.service.ts文件中,创建一个

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class MyService {

  constructor() { }
  
  public printLog () : string {
    return "这是刚创建的一个服务";
  }
  
}

二、服务使用

1.引入服务

在app.module.ts文件中,引入服务

代码如下(示例):

// 1、引入storage服务
import { MyService } from "./services/myservice.service";

2.配置服务

代码如下(示例):

// @NgModule 装饰器 
@NgModule({
  declarations: [ 
    AppComponent, 
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [MyService],//2.配置StorageService服务
  bootstrap: [AppComponent]
})
  

3.使用服务

同样,也要在使用的文件中引入服务,示例展示是在app.component.ts文件中

// 3、引入storage服务
import { MyService } from "./services/storage.service";
//@Component 装饰器
@Component({
  selector: 'app-root',//定义组件的名称
  templateUrl: './app.component.html',//定义组件html模版
  styleUrls: ['./app.component.scss']//定义组件css
})
  
//这句话表示暴露我们的组件 
export class AppComponent {
  //组件的属性 构造函数 方法 等
  constructor(public myser: MyService) {
    let s = this.myser.printLog();
    console.log(s);

  }

}

未完待续。。。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值