[英]Maintain generated token for service on injection
我正在創建一個服務來生成隨機令牌並將其傳遞給請求( 在開發人員 Spotify 中,他們強烈建議您這樣做)。 有一個查詢參數(狀態)!
這是我的服務:
import { Injectable } from '@angular/core';
@Injectable()
export class TokenService {
private _state: string;
constructor() {
alert('Token got created');
}
public get state(): string {
return this._state;
}
generateToken() {
this._state = this.randomString() + this.randomString();
alert(this._state);
}
private randomString() {
return Math.random().toString(36).substring(2);
}
}
我在這里稱它為:
...
@Injectable()
export class AngularSpotifyService {
...
constructor(private windowRef: WindowService, private token: TokenService) { }
getToken(windowName = this.name, windowOptions = this.getOptions()) {
this.windowRef.nativeWindow.open(`https://accounts.spotify.com/authorize?${this.toQueryString()}`,
windowName, windowOptions);
}
private toQueryString(): string {
this.token.generateToken();
return `client_id=${this.clientId}&response_type=${this.responseType}&redirect_uri=${this.redirectUri}&state=${this.token.state}`;
}
這兩個服務被創建了兩次,分別是在啟動應用程序時和來自 Spotify 的響應到達時。
預期行為:我正在生成一個隨機字符串來填充狀態查詢參數。 當響應到達時,我期望令牌服務不會再次創建(我認為這是正常行為),因為如果是這樣,它將生成一個新的隨機字符串,然后是狀態查詢參數(再次返回Spotify 響應)不再相等。
這是我的 app.module:
...
@NgModule({
declarations: [
AppComponent,
TokenComponent,
AngularSpotifyComponent
],
imports: [
BrowserModule,
RouterModule.forRoot(appRoutes)
],
providers: [WindowService, AngularSpotifyService, TokenService],
exports: [ RouterModule ],
bootstrap: [AppComponent]
})
export class SpotifyModule { }
您可以通過類/服務中的靜態屬性( “對象初始值設定項” )執行此操作。 我做了這個plunkr來演示。
但關鍵是變量聲明是在構造函數之外完成的,並且是在類的“啟動”時間計算的,因此多次實例化它不會影響值。
export class Example{
static value: string = Math.random().toString(36).substring(2);
constructor(){
console.log(Example.value);
}
public getValue(){
return Example.value;
}
}
this.example1 = new Example();
this.example2 = new Example();
// NOW!
this.example1.getValue() == this.example2.getValue()
所以只是為了澄清我的觀點......
替換private _state: string;
使用上面的類,然后在您之前使用_state
任何地方使用example.getValue()
。
因此,新服務將如下所示:
@Injectable()
export class TokenService {
private example: Example;
constructor() {
this.example = new Example();
alert('Token got created');
}
public get state(): string {
return this.example.getValue();
}
}
顯然,您可能會將 Example 類重命名為您認為合適的任何名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.