【问题标题】:in one component have an array. and want the other component to have access to this array. they aren't parent-child. i am using routing在一个组件中有一个数组。并希望其他组件能够访问此数组。他们不是亲子。我正在使用路由
【发布时间】:2021-12-29 10:54:42
【问题描述】:

我想从这个组件传递 addedToCart 数组

export class ProductComponent implements OnInit {
  ***
  addedToCart: Item[] = [];
  constructor(private data: DataService) { }


  addToCart(product:Item){
  ***
}
  ngOnInit(): void {
    this.data.getData()
    .subscribe(
      response =>{
        this.products = response
      }
    )
  }

}

我希望这个组件能够获取该数据。有什么简单的方法吗?

    export class CartComponent implements OnInit {
      cartItems:Item[] | undefined;
      constructor() { }
    
      ngOnInit(): void {
      }
    
    }

【问题讨论】:

    标签: angular typescript service components message-passing


    【解决方案1】:

    在这种情况下,您可以使用行为主体为您完成工作。

    创建一个在整个应用程序中使用的通用服务文件。

    在通用服务文件中,可以这样做:

    @Injectable({
      providedIn: 'root'
    })
    export class CommonService {
    
    
    initialValuesForProductsArray: string[] = [];
    
    productsArraySource: BehaviorSubject<string[]> = new BehaviorSubject<string[]>(this.initialValuesForProductsArray);
    
    productsArrayObservable: Observable<string[]> = this.productsArraySource.asObservable();
    
    constructor() {}
    
    setProductsArray(data: string[]) {
      this.productsArraySource.next(data);
    }
    
    getProductsArray(): Observable<string[]> {
      return this.productsArrayObservable;
    }
    
    }
    

    现在在您的组件中,执行以下操作:

    
    export class ProductComponent implements OnInit {
      ***
      addedToCart: Item[] = [];
      constructor(
         private data: DataService,
         private commonService: CommonService <<<<<<<<<<< ADD THIS LINE >>>>>>>>
      ) { }
    
    
      addToCart(product:Item){
      ***
    }
      ngOnInit(): void {
        this.data.getData()
        .subscribe(
          response =>{
            this.products = response;
            this.commonService.setProductsArray(this.products); <<<<<<< ADD THIS LINE >>>>>>
    
          }
        )
      }
    
    }
    

    在您想要获取此数据的组件中,执行以下操作:

        export class CartComponent implements OnInit {
          cartItems:Item[] | undefined;
          constructor(private commonService: CommonService) {} <<<<< ADD THIS LINE >>>>
        
          ngOnInit(): void {
            <<<<<<<< ADD BELOW LINES >>>>>>>>
            this.commonService.getProductsArray().subscribe(data => {
               if (data && data.length) {
                  this.cartItems = data;
               }
            });
          }
        
        }
    

    这就是你如何使用,设置行为主体,获取组件之间的数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-06
      相关资源
      最近更新 更多