角度2:从服务返回数据时未定义

时间:2018-12-27 10:40:38

标签: javascript angular typescript angular2-services

我正在使用服务进行http调用,然后将响应返回到在进行控制台时得到“未定义”的组件。我设置了超时时间,以确保http请求在控制台打印之前完成,但是没有任何运气。我是Angular 2的新手,如果有人可以帮助我,我将不胜感激。     我的密码:

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { LoginComponent } from './login/login.component';

    @Injectable({
      providedIn: 'root'
    })
    export class LoginService {    

      rootUrl = 'https://dev-510009.oktapreview.com/'
      constructor(public _http: HttpClient){

      }
      primaryVerify1(userData) {
        let data = {
          "username": userData.username,
          "password": userData.pass,
          "options": {
            "multiOptionalFactorEnroll": true,
            "warnBeforePasswordExpired": true
          } 
        };
       this._http.post(this.rootUrl + "api/v1/authn", data, {
         headers: {
           'Content-type': 'application/json'
         }
       }).subscribe(response => {
         if(response.status == 'SUCCESS'){
          let primaryverifydata = response
           console.log("primaryverifydata", primaryverifydata)
           let data1 = {
              "factorType": "token:software:totp",
              "provider": "GOOGLE"
           }
           this._http.post(this.rootUrl + "api/v1/users/"+ primaryverifydata._embedded.user.id + "/factors", data1,
           {
             headers: {
               'Content-type': "application/json",
               'Authorization' :'SSWS 00e1Wq_tDwvikJt2ZufC0DgW58JX61R6BEQriGsvtl',
               'Accept': "application/json"
             }
           }).subscribe(response => {
             console.log(response)
             let enrollResponse = response;
             if(response.status = 'PENDING_ACTIVATION'){
               window.open(enrollResponse._embedded.activation._links.qrcode.href, '_blank')
               return response;
             }

           })
         }
       })
      }


}

我的组件代码:

    import { Component, OnInit } from '@angular/core';

    import { LoginService } from '../login-service.service';

    @Component({
      selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.css'],
         providers: [LoginService],
    })
    export class LoginComponent implements OnInit {
         userData: object;
      pass: any;
        enrollResponse: object;
    constructor(private loginservice: LoginService) {
        this.userData = {};
        this.pass = "";
        this.enrollResponse = {}
       }
        ngOnInit(){
          /*  this.enrollResponse = this.loginservice.primaryVerify;
            console.log(" this.enrollResponse",  this.enrollResponse)*/
        }
        primaryVerify(){
            let some = this.loginservice.primaryVerify1(this.userData);
            setTimeout(() => {
                 console.log("this.enrollResponse", some)
            },5000)

        }
    }
Kindly note: primaryVerify() gets fired when user clicks on submit button.

2 个答案:

答案 0 :(得分:0)

primaryVerify1不返回任何内容,因此应该是undefined

您应该使用回调或Promise。类似于:

primaryVerify1(userData, callback) {
  ...
         let enrollResponse = response;
         if(response.status = 'PENDING_ACTIVATION'){
           window.open(enrollResponse._embedded.activation._links.qrcode.href, '_blank')
           callback(response);
         }

并像这样使用它:

let some = this.loginservice.primaryVerify1(this.userData, function(res) {
  console.log("this.enrollResponse", res);
});

当然这不能很好地处理错误(您可能希望尽早返回每种错误),但是它为您提供了一个起点。

答案 1 :(得分:0)

  1. 在服务primaryVerify1()中使用switchMap,因为您要依次调用http请求。那会杀死以前的可观察物。

  2. 不要订阅您的服务,而是订阅您的组件,只map来自服务的结果(即从服务返回resp)。在下面的代码中记下3个返回关键字。

  3. setTimeout()在组件中不是必需的,而是订阅primaryVerify1()

服务代码:

primaryVerify1(userData) {
        ...........
       return this._http.post(this.rootUrl + "api/v1/authn", data, {
         headers: {
           'Content-type': 'application/json'
         }
       }).pipe(switchMap(response => {
         if(response.status == 'SUCCESS'){
          ...............
           return this._http.post(this.rootUrl + "api/v1/users/"+ primaryverifydata._embedded.user.id + "/factors", data1,
           {
             headers: {
               'Content-type': "application/json",
               'Authorization' :'SSWS 00e1Wq_tDwvikJt2ZufC0DgW58JX61R6BEQriGsvtl',
               'Accept': "application/json"
             }
           }).pipe(map(response => {
             ...........
               return response;
             }))

           })
         }
       }))
    }

组件

primaryVerify(){
     let some = this.loginservice.primaryVerify1(this.userData).subscribe(data => console.log(data));
}