如何将component.ts中的数据存入其他变量及全局变量?
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

