【问题标题】:Why Angular 6 doesn't send HTTP Get/Post requests?为什么 Angular 6 不发送 HTTP Get/Post 请求?
【发布时间】:2018-08-05 07:45:07
【问题描述】:

我在 Angular 6 中有以下服务:

@Injectable()
export class LoginService {
    constructor(private http: HttpClient) { }

    login(): Observable<boolean> {
        var url = `${environment.baseAPIUrl}${environment.loginUrl}`;

        return this.http.get<boolean>(url);
    }
}

我从我的组件中调用它:

@Component({
    selector: 'bpms-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

    constructor(private loginService: LoginService) { }

    ngOnInit() {
    }

    login() {
        var self = this;
        self.loginService.login();
    }
}

为什么它不发送我的请求?

【问题讨论】:

  • 你必须订阅Observable .. 它应该是self.loginService.login().subscribe()

标签: angular typescript httpclient angular6


【解决方案1】:

Observable 在您订阅之前不会被调用。 Http API 方法返回 Observable,仅仅通过调用 observable 不会进行 API 调用。

self.loginService.login().subscribe(
  (data) => console.log('Logged in successfully')
);

【讨论】:

    【解决方案2】:

    订阅返回的 observable 之前不会进行 Http 调用。

    @Component({
    selector: 'bpms-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss']
    })
    export class LoginComponent implements OnInit {
    
    constructor(private loginService: LoginService) { }
    
    ngOnInit() {
    }
    
    login() {
        var self = this;
        self.loginService.login().subscribe();
     }
    }
    

    【讨论】:

      【解决方案3】:

      您应该调用您的login() 函数,例如在ngOnInit() 或表单提交事件中,请务必调用它。

      并更新您的 login() 函数,如下所示:

      login() {
          this.loginService.login()
              .subscribe((res) => console.log('login() response!'));
       }
      

      【讨论】:

        【解决方案4】:

        如果你的返回类型是 Observable 你需要订阅它,以便在它准备好后得到响应。所以你的代码会是这样的

        @Component({
        selector: 'bpms-login',
        templateUrl: './login.component.html',
        styleUrls: ['./login.component.scss']
        })
        export class LoginComponent implements OnInit {
        
        constructor(private loginService: LoginService) { }
        
        ngOnInit() {
        }
        
        login() {
            var self = this;
            self.loginService.login().subscribe();
         }
        }
        

        【讨论】:

          猜你喜欢
          • 2015-08-06
          • 2018-08-04
          • 1970-01-01
          • 1970-01-01
          • 2019-09-15
          • 2015-08-22
          • 1970-01-01
          • 2017-08-09
          • 1970-01-01
          相关资源
          最近更新 更多