Angular2.0—服务

Angular2.0—服务

  1. 首先使用脚手架创建项目

友情链接:Angular2.0 —构建项目的流程以及使用ng-zorro

  1. 创建组件home

友情链接:Angular2.0—路由跳转

3 .编写代码
服务类似于插件,使用频率较高的代码,做成一个服务,在其他模块直接调用

创建服务   ng  g  service  test
// 在test.service.ts中定义一个属性和方法

import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class TestService {
  title="公共属性";
  constructor() { }
  say(){
    console.log("我是公共方法");
  }
}

// 在组件中引入服务,并使用服务
import { Component, OnInit } from '@angular/core';
import { TestService } from '../test.service';
@Component({
  selector: 'app-zizujian',
  templateUrl: './zizujian.component.html',
  styleUrls: ['./zizujian.component.scss']
})
export class ZizujianComponent implements OnInit {
  constructor(
    private ser:TestService
  ) { }
  ngOnInit() {
    console.log(this.ser.title);//使用服务中得到的属性
  }
  send(){
    this.sends.emit(this.msg)
  }
  say(){
    this.ser.say();
  }
}

你可能感兴趣的:(Angular2.0—服务)