角度2:将数据从服务传递到组件

时间:2018-12-29 08:56:34

标签: angular typescript angular-services angular-components

我有一个登录页面组件,也有一个登录服务,通过该服务我可以进行HTTP调用并获取一些数据。在按钮上的login.component.html中,单击i触发一个函数,该函数依次触发服务中定义的函数。所有这些工作都很好。 现在,我还有另一个组件需要使用该登录服务中的数据。 我认为必须有一种在同级组件之间传递数据或直接从服务传递到其他组件的方法。 我已经阅读了很多有关数据共享的资源,并且了解了这些资源,但是我无法在当前的项目中实施。在我仍处于Angular2学习阶段时,有人可以帮我这个忙吗?

登录服务代码:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { LoginComponent } from './login/login.component';
import { switchMap, map } from 'rxjs/operators';
import { pipe } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class LoginService {
  //primaryverifydata: object;
  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
      }
    };
    return this._http
      .post(this.rootUrl + 'api/v1/authn', data, {
        headers: {
          'Content-type': 'application/json'
        }
      })
      .pipe(
        switchMap(response => {
          if (response.status == 'MFA_ENROLL') {
            let primaryverifydata = response;
            console.log('primaryverifydata', primaryverifydata);
            let data1 = {
              factorType: 'token:software:totp',
              provider: 'GOOGLE'
            };
            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 => {
                  if ((response.status = 'PENDING_ACTIVATION')) {
                    let enrollResponse = response;
                    window.open(
                      enrollResponse._embedded.activation._links.qrcode.href,
                      '_blank'
                    );
                    return response;
                  }
                })
              );
          }
        })
      );
  }
}

登录组件代码:

import { Component, OnInit } from '@angular/core';
import { LoginService } from '../login-service.service';
import { RouterModule, Routes, Router } from '@angular/router';
@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, private router: Router) {
    this.userData = {};
    this.pass = '';
    this.enrollResponse = {};
  }
  ngOnInit() {}

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

第二个组件(需要数据的地方):

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

@Component({
  selector: 'app-mfa',
  templateUrl: './mfa.component.html',
  styleUrls: ['./mfa.component.css']
})
export class MFAComponent {
  code: string;
  rootUrl = 'https://dev-900317.oktapreview.com/';
  constructor(public _http: HttpClient) {
    this.code = '';
  }
  verify() {
    let data = {
      passCode: this.code
    };
  }
}

1 个答案:

答案 0 :(得分:0)

如果第二个组件是第一个组件,则使用ViewChild批注或创建共享资源,然后让他们从那里获取数据。