Angular 为注入时的服务维护生成的令牌
我正在创建一个服务来生成一个随机令牌并将其传递给一个请求()。有一个查询参数(状态) 这是我的服务:Angular 为注入时的服务维护生成的令牌,angular,typescript,angular5,Angular,Typescript,Angular5,我正在创建一个服务来生成一个随机令牌并将其传递给一个请求()。有一个查询参数(状态) 这是我的服务: import { Injectable } from '@angular/core'; @Injectable() export class TokenService { private _state: string; constructor() { alert('Token got created'); } public get state
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响应一起返回)不再相等
这是我的应用程序模块:
...
@NgModule({
declarations: [
AppComponent,
TokenComponent,
AngularSpotifyComponent
],
imports: [
BrowserModule,
RouterModule.forRoot(appRoutes)
],
providers: [WindowService, AngularSpotifyService, TokenService],
exports: [ RouterModule ],
bootstrap: [AppComponent]
})
export class SpotifyModule { }
您可以通过类/服务中的静态属性()实现这一点。我做这个是为了演示 但关键是变量声明是在构造函数之外完成的,并且是在类的“启动”时间内计算的,因此多次实例化它不会影响值
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\u状态:字符串使用上面的类编写>代码,然后在前面使用\u 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();
}
}
显然,您可能会将示例类重命名为您认为合适的名称。您在哪里注册服务?在模块中?在应用程序组件中?在其他一些组件中?在app.module.I中,我用app.module更新了问题。这个答案只有一个问题,您正在创建两个示例实例,即class(并且您正在使用new关键字),在我的示例中,我正在使用服务生成令牌。这里的问题是Angular上的服务是单例的(它们在整个应用程序中共享同一个实例)。但正如我在问题中所说的,我面临着一些古怪的行为。很抱歉,你的解决方案根本不起作用。当Spotify的响应到达时,服务被重新执行或重新创建,因此这一行:static value:string=Math.random().toString(36).substring(2)被第二次计算,记住这两个值不再相等@Luillyfe我刚刚用一个工作示例更新了plunkr。