1. service传参-(补:发布订阅 + Observable可观察者对象)
ng g service event
@Injectable({providedIn:'root'})export class EventService{// 构建Subject的实例,用来完成事件的发布和订阅private subject = new Subject < any > ();constructor() {}publish(value: any, err: any) {if (value !== undefined) {// 将新的事件放入next队列中this.subject.next(value);}if (err !== undefined) {// 将错误放入error队列this.subject.error(err);}// 表示当前事件结束this.subject.complete();}subcribe(handler: {next: (value) => void,error: (err) => void,complete: () => void}) {this.subject.asObservable().subcribe(handler);}}
在app.module.ts注册
@NgModule({declarations:[],import:[],providers:[EventService],bootstrap:[AppComponent]})export class AppModule{}
使用
组件A
export class AComponent implements OnInit{constructor(private event:EventService){}ngOnInit() {}someThingChanged(data) {// 发布事件this.event.publish({// 可以定义一个事件类型,实现多个不同类型事件的发布type: 'event_type_you_want_define',// 可以携带任何数据,并通过事件发布出去data: data,ohter: 'ohter things you want to pass out'}, err);}}
组件B
export BComponent implements OnInit {constructor(private event: EventService) { }ngOnInit() {// 在初始化方法中,可以完成对事件的订阅工作this.event.subject({next: value => {// 可以通过约定事件类型,在这里进行检查,从而完成不同的逻辑// do something with value},error: err => {// handle err},complete: () => {// handle complete}})}}
- 父子组件传参(import outport)
父级->子级
父组件
<app-search [options]="StatusStr"></app-search>
子组件
@import() options:Array<string>
子级->父级
- 使用Output
子组件:
import { Component, Output, EventEmitter } from '@angular/core';@Output() search = new EventEmitter<string>();onSearch(keycode, val) {if (keycode == 13) {this.search.emit(val);}}
父组件
<app-search (search)="searchUser($event)"></app-search>
使@ViewChild
父组件
<app-search #footerChild></app-search>
import {Component,OnInit,ViewChild} from '@angular/core'@ViewChild('footerChild',{static:false}) footer
- 根据url传参(routLink)
queryParams: {
_id: id}
}
this.router.navigate([/CI-Dashboard/cw-detail], routerParams);
接收参数:this.stockId=this.routerInfo.snapshot.queryParams[“id”]
- 传参: {path:'stocks/:id',component:StocksComponent}接收参数:this.stockId=this.routerInfo.snapshot.params["id"]- 传参:{path:'stocks',component:StocksComponent,data:[{ispro:true}]}接收参数:this.stockId = this.routerInfo.snapshot.data[0]["ispro"];
