在Angular 12中,可以通过以下步骤将REST数据返回给observable,并在APP_INITIALIZER上应用逻辑:
npm install @angular/common@12.0.0
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class DataService {
constructor(private http: HttpClient) {}
getData(): Observable<any> {
return this.http.get('https://api.example.com/data');
}
}
import { APP_INITIALIZER } from '@angular/core';
import { DataService } from './data.service';
export function initializeApp(dataService: DataService) {
return () => dataService.getData().toPromise();
}
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { DataService } from './data.service';
import { initializeApp } from './app.initializer';
@NgModule({
imports: [HttpClientModule],
providers: [
DataService,
{
provide: APP_INITIALIZER,
useFactory: initializeApp,
deps: [DataService],
multi: true
}
]
})
export class AppModule { }
现在,当你的应用程序启动时,APP_INITIALIZER将调用initializeApp函数,该函数将使用DataService获取REST数据并应用逻辑。你可以在组件中订阅DataService返回的observable来处理数据。
请注意,以上代码示例中的URL和服务名称仅作为示例,你需要根据你的实际情况进行修改。
推荐的腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云