Angular7 - 将组件注入另一个组件

2024-04-26

在另一个组件中注入组件来访问注入组件中的函数或属性是否正确?
注意:这些组件都不是另一个组件的子组件

import { UsersComponent } from './../users/users.component';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  constructor(users:UsersComponent){
    users.getAllUsers()
  }
}

实际上你不能这样做。在 Angular 中,我们将一切都视为组件。如果多个组件使用任何方法或属性,您可以遵循以下方法。因为您的组件不作为子父级相关。您可以按照方法 3 和 4 进行操作。

1. 父母对孩子和孩子对父母:通过@Input和@Output共享数据

这是在组件之间共享数据最常用的方式。它使用 @Input() 装饰器。您还可以使用 @Output() 装饰器将事件传递给父级。

父组件.ts:

@Component({
  selector: 'app-parent',
  template: `
    <p>{{ message }}</p>
    <app-child [input]="parentData" (output)="childMsg($event)"></app-child>`
})
export class ParentComponent{
  message: string;
  parentData = "message from parent"
  childMsg(event) {
    this.message = event;
  }
}

子组件.ts:

@Component({
  selector: 'app-child',
  template: `
    <p>{{ input }}</p>
    <button (click)="submit()">Submit</button>
  `
})
export class ChildComponent {

  @Input() input: string;
  @Output() output = new EventEmitter<string>();
  message: string = "Hello World!"
  submit() {
    this.output.emit(this.message)
  }
}

2. 孩子对家长:通过 ViewChild 共享数据

@ViewChild 装饰器允许将一个组件注入到另一个组件中,从而使父组件能够访问其属性和方法。

父组件.ts

@Component({
  selector: 'app-parent',
  template: `
    Message: {{ childData }}
    <app-child></app-child>
  `,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements AfterViewInit {

  @ViewChild(ChildComponent) child;    

  childData: string;

  ngAfterViewInit() {
    this.childData = this.child.message
  }
}

子组件.ts:

@Component({
  selector: 'app-child',
})
export class ChildComponent {

  childData = 'Hola Mundo!';

}

注意:我们使用 AfterViewInit lifeCycle 因为子视图在视图初始化之前不可用。

3.使用Service的不相关组件:在具有服务和行为主体的不相关组件之间共享数据

公共服务.ts:

@Injectable()
export class CommonService {
  private data = new BehaviorSubject('default data');
  data$ = this.data.asObservable();

  changeData(data: string) {
    this.data.next(data)
  }
}

组件一.组件.ts:

@Component({
  selector: 'app-component-one',
  template: `<p>{{data}}</p>`
})
export class ComponentOneComponent implements OnInit {

  data: string;

  constructor(private service: CommonService) { }

  ngOnInit() {
    this.service.data$.subscribe(res => this.data = res)
  }

}

组件-two.component.ts:

@Component({
  selector: 'app-component-two',
  template: `
    <p>{{data}}</p>
    <button (click)="newData()">Next Data</button>`
})
export class ComponentTwoComponent implements OnInit {

  data: string;

  constructor(private service: CommonService) { }

  ngOnInit() {
    this.service.data$.subscribe(res => this.data = res)
  }
  newData() {
    this.service.data.next('Changed Data');
  }
}

4、状态管理:使用 NgRx 在不相关的组件之间共享数据 您可以使用 NgRx 之类的存储来管理状态,您将在其中存储您的财产,然后在任何地方使用。我学习ngrx的时候就遵循了这个例子。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular7 - 将组件注入另一个组件 的相关文章

随机推荐