Angular4服务传参方案问询:参数构建位置与URL参数配置
Hey there! Let's break down your questions step by step and fix up your code to get that parameter flow working smoothly.
一、Should Parameters Be Built in the Component or Service?
- Components handle collecting raw parameter values: It makes sense to gather parameters from UI interactions (like your dropdown selection), page state, or route data in the component. This keeps the component focused on its job: connecting the user interface to your app's logic.
- Services handle formatting parameters for the API: The service should take the raw values from the component and shape them into the format the backend expects—like encoding URL parameters, adding default values, or structuring payloads. This way, your service stays dedicated to API communication, and you can reuse it across multiple components without duplicating logic.
二、How to Build URL Parameters for a PHP Server
Angular 4's Http module (note: if you're on Angular 4.3+, using HttpClient is recommended, but I'll cover both for your code) doesn't accept raw data as the second argument for get()—you need to use a configuration object with parameter settings. Here's how to adjust your code:
1. Update Your Service Code (service.ts)
First, import the right tools to build URL parameters:
import { Http, Response, URLSearchParams } from '@angular/http'; // Keep your other imports... listOfData(transNo: string): Observable<any> { // Build the URL query parameters const params = new URLSearchParams(); params.set('transNo', transNo); // Match this key to what your PHP code expects (e.g., $_GET['transNo']) // Pass params via the `search` property in the request config return this.http.get(`${this.API_ROOT}${this.API_LIST}`, { search: params }) .map((res: Response) => res.json() || {}) .catch(this.handleError); }
If you've upgraded to HttpClient (Angular 4.3+), the code is cleaner:
import { HttpClient, HttpParams } from '@angular/common/http'; // Keep your other imports... listOfData(transNo: string): Observable<any> { const params = new HttpParams().set('transNo', transNo); return this.http.get(`${this.API_ROOT}${this.API_LIST}`, { params }) .pipe( map(res => res.records || {}) ) .catch(this.handleError); // Or use pipe(catchError(...)) for newer RxJS versions }
2. Tweak Your Component Code (component.ts)
Your component logic is almost there—just make sure you're passing the correct parameter value when calling the service. For example, add a handler for your dropdown selection:
transaction: any; selectedTransNo: string; // Bind this to your dropdown myList(transNo) { this.service.listOfData(transNo).subscribe( (data) => { this.source.load(data.records); this.dataLoaded = true; }, ); } onDropdownChange() { // Trigger the service call when the user selects an option this.myList(this.selectedTransNo); } ngOnInit() { this.settings = Object.assign({}, this.WorkshopDetailsSetting); // Set a default transaction to load on init this.selectedTransNo = '1'; this.myList(this.selectedTransNo); this.optionsSelect = [ { value: '1', label: 'Transaction 1' }, { value: '2', label: 'Transaction 2' }, { value: '3', label: 'Transaction 3' }, { value: '4', label: 'Transaction 4' }, { value: '5', label: 'Transaction 5' }, { value: '6', label: 'Transaction 6' } ] }
3. PHP Side: Receive the Parameter
In your PHP script, use the $_GET superglobal to access the URL parameter:
<?php $transNo = $_GET['transNo']; // Process your data logic here // Return JSON response matching what your Angular code expects header('Content-Type: application/json'); echo json_encode([ 'records' => [/* Your fetched data here */] ]); ?>
Quick Recap
- Components provide the raw parameter values, services handle formatting them for the API—this keeps your code organized and reusable.
- Always use
URLSearchParams(oldHttp) orHttpParams(HttpClient) to build GET request parameters in Angular—don't pass raw data directly toget().
内容的提问来源于stack exchange,提问作者Manish Agarwal

