如何解决Angular HttpClientModule在页面加载时未发出HTTP请求
我无法解决新升级的Angular 10的问题。我之所以说Angular 10,是因为它在Angular 9中有效。尽管从变更日志等开始,我仍无法弄清该应用为何如此运行。 我基本上有一个登录页面,登录页面将带您进入应用程序的主仪表板视图。当用户登录时,假设是发出http请求以获取某些仪表板小部件数据等,但事实并非如此。令人费解的是,如果刷新仪表板页面,则它确实会发出http请求。仅当它不发出http请求时才从登录页面进入仪表板页面。所以我不确定我是不是正确地或以正确的顺序加载了依赖项,还是什么...
这是我的signin.component.ts-成功登录后导航到仪表板视图的地方
this.authStatusSub = this.authService.getAuthStatusListener()
.subscribe(authObject=>{
if(!authObject) {
if(authObject.authenticated === false) {
this.toastr.error('User cannot be authenticated','Login failed');
this.loading = false;
return;
}
} else if (authObject.authenticated === true) {
this.store.setItem("login_status",true);
if(authObject.redirectUrl) {
this.router.navigateByUrl(authObject.redirectUrl);
} else {
this.router.navigateByUrl('/dashboard/v1');
}
}
this.loading = false;
})
这是登录后加载的dashboard.component.ts。我知道这个组件是由于console.log实例化的:)我剥离了所有不相关的东西。我知道下面的代码会有错误。
import { Component,OnInit} from '@angular/core';
import { DashboardService } from 'src/app/shared/services/dashboard.service';
import { ToastrService } from 'ngx-toastr';
import { InventoryService } from 'src/app/shared/services/inventory.service';
@Component({
selector: 'app-dashboad-default',templateUrl: './dashboad-default.component.html',styleUrls: ['./dashboad-default.component.css']
})
export class DashboadDefaultComponent implements OnInit {
constructor(
private dashboardService: DashboardService,private toastr: ToastrService,private inventoryService: InventoryService) {}
ngOnInit() {
this.isLoading = true;
console.log('here')
this.dashboardService.onDashboardMain();
this.dashboardSub =
this.dashboardService.getDashboardMain()
.subscribe((res:any)=>{
console.log('here 1');
this.isLoading = false;
},(err)=> {
this.toastr.error('Error occurred in snapshot load','Error ocurred!');
this.isLoading = false;
});
}
}
它永远不会发出http请求,因此它永远不会进入.subscribe()或错误处理程序内部。
这是发出http请求的我的dashboard.service.ts文件。
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Subject } from "rxjs";
import { environment } from 'src/environments/environment';
import { LocalStoreService } from "./local-store.service";
const BACKEND_URL = environment.ApiBaseUrl +'/dashboard';
@Injectable({
providedIn: 'root'
})
export class DashboardService {
private dashboardMainSnapshot = new Subject<any>();
constructor(private http: HttpClient,private localService: LocalStoreService) {}
getDashboardMain() {
return this.dashboardMainSnapshot.asObservable();
}
onDashboardMain() {
let userName = this.localService.getItem('username');
const body = {
username: userName
}
this.http.post(BACKEND_URL+'/getDashboardMain',body)
.subscribe((res:any)=>{
this.dashboardMainSnapshot.next({status:true,dashboardSnapshot: res.content});
},(err)=>{
this.dashboardMainSnapshot.next({status:false});
})
}
}
这是我的app.module.ts文件。
import { NgModule } from '@angular/core';
import { HttpClientModule,HTTP_INTERCEPTORS } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { SharedModule } from './shared/shared.module';
import { AuthInterceptor } from './shared/services/auth-interceptor';
import { DatePipe } from '@angular/common';
import { LaddaModule } from 'angular2-ladda';
@NgModule({
declarations: [
AppComponent
],imports: [
SharedModule,HttpClientModule,BrowserAnimationsModule,ToastrModule.forRoot({
timeOut: 10000,positionClass: 'toast-top-center',preventDuplicates: true,progressBar: true
}),AppRoutingModule,LaddaModule
],providers: [
DatePipe,{
provide: HTTP_INTERCEPTORS,useClass: AuthInterceptor,multi: true
}
],bootstrap: [AppComponent]
})
export class AppModule { }
这是我的shared.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { PerfectScrollbarModule } from 'ngx-perfect-scrollbar';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { SearchModule } from './components/search/search.module';
import { SharedComponentsModule } from './components/shared-components.module';
import { SharedDirectivesModule } from './directives/shared-directives.module';
import { SharedPipesModule } from './pipes/shared-pipes.module';
@NgModule({
imports: [
CommonModule,PerfectScrollbarModule,SearchModule,NgbModule,SharedComponentsModule,SharedDirectivesModule,SharedPipesModule,RouterModule
]
})
export class SharedModule { }
最后,这是app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes,RouterModule,PreloadAllModules } from '@angular/router';
import { AuthLayoutComponent } from './shared/components/layouts/auth-layout/auth-layout.component';
import { AuthGaurd } from './shared/services/auth.gaurd';
import { AdminLayoutSidebarLargeComponent } from './shared/components/layouts/admin-layout-sidebar-
large/admin-layout-sidebar-large.component';
const adminRoutes: Routes = [
{
path: 'dashboard',loadChildren: () => import('./views/dashboard/dashboard.module').then(m => m.DashboardModule)
},{
path: 'pages',loadChildren: () => import('./views/pages/pages.module').then(m => m.PagesModule)
}
];
const routes: Routes = [
{
path: '',component: AuthLayoutComponent,children: [
{
path: 'sessions',loadChildren: () => import('./views/sessions/sessions.module').then(m => m.SessionsModule)
}
]
},{
path: '',component: AdminLayoutSidebarLargeComponent,canActivate: [AuthGaurd],children: adminRoutes
},{
path: '**',redirectTo: 'others/404'
}
];
@NgModule({
imports: [RouterModule.forRoot(routes,{ useHash: true,onSameUrlNavigation: 'reload',preloadingStrategy: PreloadAllModules})],exports: [RouterModule],providers: [AuthGaurd]//added
})
export class AppRoutingModule { }
请告知我是否需要提供其他任何组件。我已经尽力想了一切。
非常感谢您的帮助。
编辑*** 简直就是一切。在dashboard.component.ts中,回到了基础
this.dashboardSnapshotSub = this.dashboardService.onDashboardMain()
.subscribe((res:any)=>{
console.log(res);
})
Dashboard.service.ts
onDashboardMain() {
console.log('here');
return this.http.get(BACKEND_URL+'/getDashboardMain')
}
这会产生此错误,这是我在开始调试此问题之前最初得到的。
错误TypeError:散布不可迭代实例的尝试无效。 为了可迭代,非数组对象必须具有Symbol.iterator方法。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com(将#修改为@)