You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将component.ts中的数据存入其他变量及全局变量?

How to Store Data from Service into Component Variable and Make It Global in Angular

Got it, let's break down how to solve your two requirements: storing the fetched data in a component variable first, then making it accessible globally across your Angular app.

1. Store Data from get_update into a Component Variable

First, let's modify your component to hold the fetched data in a dedicated variable. Here's the updated component.ts:

import { Component, OnInit } from '@angular/core';
// Make sure to import your service correctly
import { YourDataService } from './path-to-your-service';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
  // Define a variable to hold the fetched data
  public vendorData: any[] = [];
  // Assuming `user` is defined somewhere in your component
  public user: any;

  constructor(private service: YourDataService) { }

  ngOnInit() {
    this.service.get_update(this.user).subscribe({
      next: (data) => {
        console.log(data);
        // Assign the fetched data to your component variable
        this.vendorData = data;
      },
      error: (error) => {
        console.error('Error fetching data:', error);
      }
    });
  }
}

This way, the data from get_update is stored in vendorData, which you can use anywhere within the component (like in your template with {{ vendorData }} or other logic).

2. Convert the Data into a Global Variable

To make this data accessible across multiple components, the best practice in Angular is to use a shared service with an RxJS BehaviorSubject (this lets components subscribe to updates whenever the data changes).

Step 1: Create a Global Data Service

Create a new service (e.g., global-data.service.ts):

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root' // This makes the service singleton (global)
})
export class GlobalDataService {
  // BehaviorSubject holds the current value and emits updates to subscribers
  private _globalVendorData = new BehaviorSubject<any[]>([]);
  // Expose an observable so components can subscribe to changes
  public globalVendorData$: Observable<any[]> = this._globalVendorData.asObservable();

  constructor() { }

  // Method to update the global data
  setGlobalVendorData(data: any[]) {
    this._globalVendorData.next(data);
  }

  // Optional: Get the current value without subscribing
  getCurrentGlobalVendorData(): any[] {
    return this._globalVendorData.value;
  }
}

Step 2: Update Your Component to Sync Data to the Global Service

Modify your component to inject the global service and pass the fetched data to it:

// component.ts
import { Component, OnInit } from '@angular/core';
import { YourDataService } from './path-to-your-service';
import { GlobalDataService } from './path-to-global-data-service'; // Import the global service

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
  public vendorData: any[] = [];
  public user: any;

  constructor(
    private service: YourDataService,
    private globalDataService: GlobalDataService // Inject the global service
  ) { }

  ngOnInit() {
    this.service.get_update(this.user).subscribe({
      next: (data) => {
        console.log(data);
        this.vendorData = data;
        // Sync the data to the global service
        this.globalDataService.setGlobalVendorData(data);
      },
      error: (error) => {
        console.error('Error fetching data:', error);
      }
    });
  }
}

Step 3: Access the Global Data in Other Components

In any other component that needs the global data, inject the GlobalDataService and subscribe to globalVendorData$:

// another-component.ts
import { Component, OnInit } from '@angular/core';
import { GlobalDataService } from './path-to-global-data-service';

@Component({
  selector: 'app-another-component',
  templateUrl: './another-component.component.html',
  styleUrls: ['./another-component.component.css']
})
export class AnotherComponent implements OnInit {
  public globalVendorData: any[] = [];

  constructor(private globalDataService: GlobalDataService) { }

  ngOnInit() {
    // Subscribe to the global data updates
    this.globalDataService.globalVendorData$.subscribe(data => {
      this.globalVendorData = data;
      console.log('Global data received:', data);
    });
  }
}

Note About Older Angular HTTP Code

Your get_update method uses Headers and RequestOptions which are from the older Http module. If you're using Angular 4.3+, consider switching to HttpClient which uses HttpHeaders instead (it's simpler and automatically parses JSON):

// Updated get_update with HttpClient
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';

get_update(id: any): Observable<any[]> { 
  const headers = new HttpHeaders({ 'Content-Type': 'application/json'}); 
  return this.http.get<any[]>('http://localhost:8000/vendor/'+id, { headers }) 
    .pipe(
      catchError(error => {
        console.error('Error:', error);
        throw error.statusText;
      })
    ); 
}

内容的提问来源于stack exchange,提问作者Sudharsan Venkatraj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:27:06