【问题标题】:Angular 8 how do you execute service before page loads?Angular 8 如何在页面加载之前执行服务?
【发布时间】:2020-03-01 22:30:25
【问题描述】:

我只是想在页面加载之前检索数据以便能够显示这些数据。

user.service.ts

export class UserService {

  constructor(private httpClient: HttpClient) { }

  getUserDetails(username) {
    return this.httpClient.get<User[]>(`http://localhost:8080/users/` + username)
    .pipe(
      map(
        userData => {
          console.log(userData);
          return userData;
        }
      )
    );
  }
}

account.component.ts

export class AccountComponent implements OnInit {

  username: string;

  ngOnInit(): void {
    throw new Error('Method not implemented.');
  }

  constructor(private authenticationService: AuthenticationService, private userService: UserService, private router: Router) {
    this.username = sessionStorage.getItem('username');
    this.userService.getUserDetails(this.username);
  }

  logout() {
    this.authenticationService.logOut();
  }
}

【问题讨论】:

  • 您确实意识到,httpClient 进行了异步调用,但您正在同步调用 getUserDetails,对吗?
  • account.component.ts 上,将你在构造函数上所做的放在 ngOnInit 上
  • 您可能正在寻找路由解析器。 alligator.io/angular/route-resolvers
  • @Eudz 现在它会出现在 getUserDetails() 方法中,但它什么都不做?从未到达 console.log(userDate)?
  • 你必须订阅getUserDetail()

标签: angular asynchronous


【解决方案1】:

如果我是你,为了在我的模板中获取异步数据,我会这样做:

<div *ngIf="myData !== null">
…
</div>

这个简单的技巧可以让您显示异步数据而不会出错。

【讨论】:

    【解决方案2】:

    您需要使用解析器才能做到这一点。解析器是一个实现resolve&lt;resolveType&gt; 并使用一个方法resolve 的类。在resolve 函数中,您可以使用注入服务返回带有您的数据的可观察对象:

    @Injectable({ providedIn: 'root' })
    export class userResolver implements Resolve<anu> {
      constructor(private userService: UserService) {}
    
      resolve(route: ActivatedRouteSnapshot): Observable<any>| {
        return this.userService.getUserById(route.paramMap.get('id'));
      }
    }
    

    在这个例子中,我们注入userService 并使用一个方法返回一个 Observable。请注意,我在这里使用any 进行简化。在这种情况下,route 参数包含我们正在尝试解析的当前路由。假设/user/1。我们可以使用此对象来检索有关当前路线的信息,例如用户 ID。

    然后可以在特定页面的路由中使用我们的解析器。它将在页面的onInit 函数之前运行。要将其添加到页面,您需要在其路由的resolve 部分调用该函数:

    let route =  [
          {
            path: 'user/:id',
            component: UserComponent,
            resolve: {
              hero /* the name we will use in the onInit to get the data */: Resolver /* our resolver */
            }
          }
        ])
    ...
    

    然后我们可以在onInit 函数中访问解析的数据:

    export class UserComponent {
    ...
        constructor(private route: ActivatedRoute) {}
    
        ngOnInit(){
             this.route.subscribe(data => {
                 // we do something with our data.
             });
        }
    }
    

    您可以获取更多信息at the official Angular docs

    【讨论】:

      猜你喜欢
      • 2023-04-05
      • 2010-10-27
      • 1970-01-01
      • 1970-01-01
      • 2013-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-14
      相关资源
      最近更新 更多