1-1 生成服务
ng g service services/common
1-2 在根模块中配置
//app.module.ts
import {CommonService} from './services/common.service';
@NgModule({
providers: [CommonService]
})
export class AppModule { }
1-3 组件使用服务
export class CommonService {
public defaultCity:string = "武汉"
constructor() { }
}
//1.导入服务
import {CommonService} from '../../services/common.service'
export class HomeComponent implements OnInit {
//2.构造函数中配置
constructor(public common:CommonService) { }
ngOnInit() {
//3.使用
console.log(this.common.defaultCity);
}
}