如何在 Angular 中将数据从一个组件传递到另一个组件而不创建新实例?

How to pass data from one component to another in Angular without creating new instance?

我有两个组成部分。一个对象将被添加到 Component2 内的数组中。在 smae 方法中,该对象必须传递给 Component1 内的数组。

我已经尝试过@Input 和服务,从我在这里找到的解决方案中获得帮助。但是,这些正在创建组件的新实例。数组正在重置,而不是将新对象推入其中。

有什么解决方法?无法弄清楚如何通过路由器插座正确使用@Input。

通用解决方案会很有帮助。谢谢你。

如果您正在使用路由器传递数据,则可以使用 NavigationExtras 传递数据。

import { NavigationExtras, Router } from '@angular/router';
// all the code we know here
export class AnyComponent {

constructor(private router: Router) { }

  passData(data) {
    let navigationExtras: NavigationExtras = {
      queryParams: {
      passedData: data
      };
      this.router.navigate(['whereUGo'], navigationExtras);
  }
}

然后你用激活的路由捕获另一个组件。

https://angular.io/api/router/NavigationExtras

这是信息。

您可以通过 service.

使用组件交互

组件 A:

@Component({
  selector: 'app-a',
  template: `
    <h1>A</h1>
    <p *ngFor="let item of dat">{{item}}</p>
    <button type="button" (click)="addNumber()">Add Number</button>
  `,    
})
export class AComponent implements OnInit {

  dat: Array<number> = [1, 2, 3];
  count: number;
  constructor(private service: AppService){}

  ngOnInit(){
    this.count = 3;
  }

  addNumber(){
    this.count++;
    this.dat.push(this.count);
    this.service.addNewValue(this.count);
  }
} 

组件 B:

@Component({
  selector: 'app-b',
  template: `
    <h1>B</h1>
    <p *ngFor="let item of dat">{{item}}</p>
  `,    
})
export class BComponent {
  dat: Array<number> = [1, 2, 3];
  subscription: Subscription;

  constructor(private service : AppService){
    this.subscription = this.service.newValue$.subscribe((res)=>{
      this.dat.push(res);
    })
  }
} 

服务:

export class AppService {

  private newValue = new Subject<number>();
  newValue$ = this.newValue.asObservable();

  constructor(private http: HttpClient) { }

  // Service message commands
  addNewValue(value: number) {
    this.newValue.next(value);
  }
}

演示:Stackblitz