尝试使用Promise等待HTTP get请求(Angular)

问题描述 投票:-1回答:1

我正在尝试实现一个承诺,因此我的代码将同步运行。谁能帮我找到我的错误可能在哪里?

import { Injectable } from '@angular/core';
import { CanActivate, Router, CanLoad } from '@angular/router';
import { AuthService } from 'src/app/auth.service';
import { User } from 'src/models/user';
import {ListdataService} from 'src/app/listdata.service';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class CompanyonlyService implements CanActivate {
  companieslist=[]


  constructor(private authService: AuthService, private router: Router,private dataService:ListdataService,private httpClient: HttpClient) { }



async run2(){
    let tmp = await this.httpClient.get(
      'http://########/reports/unique_companies/').toPromise().then((value) => {
        console.log(value)
        this.companieslist.push(value)
        console.log('typeof complist')
        console.log(typeof(this.companieslist))
        console.log('length')
        console.log(this.companieslist.length)
      });}


run3(){
        return this.run2()
      }

    canActivate(){

      this.run3()

      console.log(this.companieslist.length)


    if (this.companieslist.length==0) {


      this.router.navigate(['/companysignup'])


    }
    else{

      this.router.navigate(['/dashboard']);

    }


    return this.authService.isLoggedIn();

  }


    } 

当前,代码在返回this.companieslist值之前会先运行条件语句,以便所有用户最终进入公司注册页面。

angular angular-promise angular9 angular-router-guards
1个回答
0
投票

@ Munzer我得到了正确的功能,因为您为队友们欢呼!!!

 canActivate(next:ActivatedRouteSnapshot, state:RouterStateSnapshot){
        return this.httpClient.get('http://192.168.1.9:8000/reports/unique_companies/').toPromise().then(e => {
            if (e) {
              console.log('pass')

              return true;

            }
        }).catch(() => {
          console.log('fail')

            this.router.navigate(['/companysignup']);

            return false;
        });

    }   

基本上,如果我返回任何对象,则执行true语句。

© www.soinside.com 2019 - 2024. All rights reserved.