如何在 angular service.ts 中传递 fix 变量?
How to pass fix variable in angular service.ts?
我有一个 API 来获取用户 ID、姓名和一些进一步的详细信息。
现在我正在创建 POST api 来发送一些数据和 user_id。
我在不同的组件中调用 POST 服务并传递不同的值,但 User_id 在每个组件中都是相同的。
Service.ts
@Injectable({
providedIn: 'root'
})
get_user_info(){
return this.httpClient.get(this.baseUrl + '/users/user_info', { headers: headers }); <-- getting all data
}
}
send_user_preference(item) {
console.log("Checking passed item: ",item);
return this.httpClient.post(this.baseUrl + '/users-likes',item); <--- here i need data from resource + user_id
console.log("-------------------------");
}
我不想将 user_id 从父组件作为 @Import user_id 发送到每个子组件,因为它看起来是多余的,因为 user_id 是相同的。
我希望 user_id 直接到 POST 服务,无论该服务是从哪个组件调用的。
在您的服务中有一个 user_id
道具,您可以从任何组件设置它或根据您的要求在此处自行初始化它。
让你的post喜欢:
this.httpClient.post(this.baseUrl + '/users-likes', {user_id: this.user_id, ...item})
只需在执行 get 请求时使用 tap
,将其存储在您的服务中的变量中,您可以直接在 post 请求中使用。所以:
import { tap } from 'rxjs/operators';
// ...
userId;
get_user_info() {
return this.httpClient.get<any>(...).pipe(
// apply your usecase, whatever property id is stored in
tap((data) => this.userId = data.userId),
catchError( /** error handling! **/)
)
}
现在您可以在请求中使用它:
send_user_preference(item) {
console.log(this.userId) // use it how you need it!
}
现在 none 的组件需要在发出 post 请求时关心用户 ID 是什么。
还有一个与问题无关的建议:请将您的数据键入接口而不是使用 none 或 any
,同时考虑对您的 http 请求使用错误处理。
我有一个 API 来获取用户 ID、姓名和一些进一步的详细信息。 现在我正在创建 POST api 来发送一些数据和 user_id。 我在不同的组件中调用 POST 服务并传递不同的值,但 User_id 在每个组件中都是相同的。
Service.ts
@Injectable({
providedIn: 'root'
})
get_user_info(){
return this.httpClient.get(this.baseUrl + '/users/user_info', { headers: headers }); <-- getting all data
}
}
send_user_preference(item) {
console.log("Checking passed item: ",item);
return this.httpClient.post(this.baseUrl + '/users-likes',item); <--- here i need data from resource + user_id
console.log("-------------------------");
}
我不想将 user_id 从父组件作为 @Import user_id 发送到每个子组件,因为它看起来是多余的,因为 user_id 是相同的。
我希望 user_id 直接到 POST 服务,无论该服务是从哪个组件调用的。
在您的服务中有一个 user_id
道具,您可以从任何组件设置它或根据您的要求在此处自行初始化它。
让你的post喜欢:
this.httpClient.post(this.baseUrl + '/users-likes', {user_id: this.user_id, ...item})
只需在执行 get 请求时使用 tap
,将其存储在您的服务中的变量中,您可以直接在 post 请求中使用。所以:
import { tap } from 'rxjs/operators';
// ...
userId;
get_user_info() {
return this.httpClient.get<any>(...).pipe(
// apply your usecase, whatever property id is stored in
tap((data) => this.userId = data.userId),
catchError( /** error handling! **/)
)
}
现在您可以在请求中使用它:
send_user_preference(item) {
console.log(this.userId) // use it how you need it!
}
现在 none 的组件需要在发出 post 请求时关心用户 ID 是什么。
还有一个与问题无关的建议:请将您的数据键入接口而不是使用 none 或 any
,同时考虑对您的 http 请求使用错误处理。