发表于: 2019-10-17 19:53:04

1 827


今天完成的事情

Angular 中的service服务

Angualr 中的服务

创建服务命令

ng g service my-new-service

创建到指定目录下面

ng g service services/storage


app.module.ts 里面引入创建的服务

1.app.module.ts 里面引入创建的服务

import { StorageService } from './services/storage.service';


2. NgModule 里面的providers 里面依赖注入服务

@NgModule({
  declarations: [
  AppComponent,
  HeaderComponent,
  FooterComponent,
  NewsComponent,
  TodolistComponent
  ],
  imports: [
  BrowserModule,
  FormsModule
  ],
  providers: [StorageService],
  bootstrap: [AppComponent]
  })
export class AppModule { }


使用的页面引入服务,注册服务

import { StorageService } from '../../services/storage.service';


constructor(private storageStorageService) {
}


使用

addData(){
  // alert(this.username);
  this.list.push(this.username);
  this.storage.set('todolist',this.list);
  }
  removerData(key){
  console.log(key);
  this.list.splice(key,1);
  this.storage.set('todolist',this.list);
}


Angular 父子组件以及组件之间通讯

父组件给子组件传值-@input

父组件不仅可以给子组件传递简单的数据,还可把自己的方法以及整个父组件传给子组件

1. 父组件调用子组件的时候传入数据

<app-header [msg]="msg"></app-header>


2. 子组件引入Input 模块

import { ComponentOnInit ,Input } from '@angular/core';


3. 子组件中@Input 接收父组件传过来的数据

export class HeaderComponent implements OnInit {
  @Input() msg:string
  constructor() { }
  ngOnInit() {
  }
}


4. 子组件中使用父组件的数据

<h2>这是头部组件--{{msg}}</h2>


子组件通过@Output 触发父组件的方法

1. 子组件引入Output 和EventEmitter

import { ComponentOnInit ,Input,Output,EventEmitterfrom '@angular/core';


2.子组件中实例化EventEmitter

@Output() private outer=new EventEmitter<string>();
/*用EventEmitter 和output 装饰器配合使用<string>指定类型变量*/


3. 子组件通过EventEmitter 对象outer 实例广播数据

sendParent(){
  // alert('zhixing');
  this.outer.emit('msg from child')
}


4.父组件调用子组件的时候,定义接收事件, outer 就是子组件的EventEmitter 对象outer

<app-header (outer)="runParent($event)"></app-header>


5.父组件接收到数据会调用自己的runParent 方法,这个时候就能拿到子组件的数据

//接收子组件传递过来的数据
runParent(msg:string){
  alert(msg);
}


父组件通过@ViewChild 主动获取子组件的数据和方法

1.调用子组件给子组件定义一个名称

<app-footer #footerChild></app-footer>


2. 引入ViewChild

import { ComponentOnInit ,ViewChildfrom '@angular/core';


3. ViewChild 和刚才的子组件关联起来

@ViewChild('footerChild'footer;


4.调用子组件

run(){
  this.footer.footerRun();
}


非父子组件通讯

1、公共的服务

2、Localstorage (推荐)

3、Cookie


今天遇到的问题

暂无


今天的收获

学习了angular中的service服务和父子组件之间的通讯


明天的计划

继续学习angular框架



返回列表 返回列表
评论

    分享到