简体   繁体   English

当app-routing模块加载组件时,ngOnit没有被执行

[英]ngOnit is not executed when when the app-routing module loads the component

This ngOnInit does not execute the console.log line此 ngOnInit 不执行 console.log 行

ngOnInit() {
  this.loadBlogPosts();
  this.authStatusService.getAuthUsername().subscribe(
    status => {
      // got username status
      console.log("This is the username status from home", status);
      this.authUsername = status;
    }
  );
}

This line is executed这一行被执行

this.loadBlogPosts();

This line is not executed:此行不执行:

console.log("This is the username status from home", status);

This is the app-module.ts.这是 app-module.ts。

const routes: Routes = [
  { path: '', component: HomeComponent, pathMatch: 'full' },

  { path: 'home', component: HomeComponent },
  { path: 'add', component: BlogPostAddEditComponent  },
  { path: 'posts', component: BlogPostsComponent },
  { path: 'post', component: BlogPostComponent },
  { path: 'auth', component: AuthComponent },
  { path: 'blogpost/:id', component: BlogPostComponent },
  { path: '**', redirectTo: '/' }
];



This is the app.component.html这是app.component.html

<app-headernav></app-headernav>
<router-outlet></router-outlet>

This is the service:这是服务:

export class AuthStatusService {

  authUsernameChange: Subject<string> = new Subject<string>();

  constructor() { }


  public getAuthUsername(): Observable<string> {
     return this.authUsernameChange.asObservable();
   }

   public setAuthUsername(user: string) {
       this.authUsernameChange.next(user);
     }
}

There's nothing wrong with ngOnInit here.这里的ngOnInit没有任何问题。 this.authStatusService.getAuthUsername() returns an observable, so the handler in this code: this.authStatusService.getAuthUsername()返回一个 observable,所以这段代码中的处理程序:

this.authStatusService.getAuthUsername().subscribe(
    status => {
      // got username status
      console.log("This is the username status from home", status);
      this.authUsername = status;
    }
  );

will only execute when the observable emits a new value.只会在 observable 发出新值时执行。 ngOnInit is only registering the observable handler method. ngOnInit仅注册可观察的处理程序方法。 You need to emit a value somewhere after the call to ngOnInit maybe with this.authStatusService.setAuthUsername(something) ;您需要在调用ngOnInit之后的某处发出一个值,可能使用this.authStatusService.setAuthUsername(something) If you need the last emitted value you should use a BehaviorSubject instead of Subject in authUsernameChange如果您需要最后发出的值,您应该在authUsernameChange中使用BehaviorSubject而不是Subject

 authUsernameChange: BehaviorSubject <string> = new BehaviorSubject <string>(initialValue);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM