Skip to content

How to import outlook contacts to ionic app – Draft

1. Login to Microsoft developer console or you can directly go to the console by clicking following link and crate a application with desired name.

2. Grab the application client ID and secret keys from the Microsoft developer app control panel.

3. Now install In App Browser – Install the Cordova and Ionic Native plugins with below commands

$ ionic cordova plugin add cordova-plugin-inappbrowser
$ npm install --save @ionic-native/in-app-browser

4. After installing a plugin’s package called in-app-browser, add it to your app’s NgModule and also import HttpModulesrc/app/app.module.ts.

...

import { InAppBrowser } from '@ionic-native/in-app-browser';
import { HttpModule } from '@angular/http';

...

@NgModule({
  ...
 imports: [
    ....
    HttpModule,
    ...
  ],
  providers: [
    ...
    InAppBrowser,
    ...
  ]
  ...
})
export class AppModule { }

4.For the sake of simplicity lets use our home page component(src/pages/home/home.ts), add in App Browser to the home module as shown below.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { InAppBrowser } from '@ionic-native/in-app-browser';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController, private iab: InAppBrowser) { 
    
  }

}

5. Add the button in the home screen to initiating the authorization code/token request. After adding button my home page html will become like below shown.


  
    Home
  



  

Welcome to Ionic!

5. Now define your outlookLogin() method in the home component.

import { Component } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';
import { InAppBrowser } from '@ionic-native/in-app-browser';
declare var window: any;
import { Observable } from 'rxjs/Rx';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  outlookClientID = '';
  outlookClientSecret = '';
  outlookRedirectUrl = '';

  OutlookContactsList: any;
  constructor(public navCtrl: NavController, private iab: InAppBrowser, private platform: Platform, private http: Http) {

  }

  outlookLogin() {
    this.platform.ready().then(() => {
      this.outLookLogin().then(code => {

        const credentials = `client_id=${this.outlookClientID}
        &client_secret=${this.outlookClientSecret}&redirect_uri=${this.outlookRedirectUrl}
        &grant_type=authorization_code
        &code=${code}`;

        var headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        this.http.post('https://login.microsoftonline.com/common/oauth2/v2.0/token', credentials, { headers: headers })
          .map(res => res.json())
          .subscribe(data => {
            const headers = new Headers();
            headers.append('Content-Type', 'application/x-www-form-urlencoded');
            headers.append('Authorization', `Bearer ${data.access_token}`);
            this.http.get('https://graph.microsoft.com/beta/me/people/?$skip=0&$top=1000', { headers: headers })
              .map((response: Response) => response.json()
                .subscribe((rows: any) => {
                  this.OutlookContactsList = rows;
                }, error => {
                  console.log(error);
                })
              , (error) => {
                return error;
              });
          }, (error) => {
            console.log(error);
          });
      });
    });
  }

  outLookLogin(): Promise {
    return new Promise((resolve, reject) => {

      const url = `https://login.microsoftonline.com/common/oauth2/v2.0/authorize?
      state=Eav6wrDocSdnkKHfvdzBs9XmtE2SitGd
      &scope=profile+openid+email+offline_access+User.Read+Mail.Send+Contacts.ReadWrite.Shared
      &response_type=code
      &approval_prompt=auto
      &client_id=${this.outlookClientID}
      &redirect_uri=${this.outlookRedirectUrl}`;

      var browserRef = window.cordova.InAppBrowser.open(url, "_blank", "location=no,clearsessioncache=yes,clearcache=yes");
      browserRef.addEventListener("loadstart", (event) => {
        if ((event.url).indexOf(this.outlookRedirectUrl) === 0) {
          browserRef.removeEventListener("exit", (event) => { });
          browserRef.close();
          let code = getParameterByName('code', event.url);
          if (code) {
            resolve(code);
          } else {
            reject("Problem authenticating with outlook");
          }
        }
      });
      browserRef.addEventListener("exit", function (event) {
        reject("The Outlook sign in flow was canceled");
      });
    });
  }

}

// to get query string form the auth url of outlook
function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, "\\$&");
  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, " "));
}

0 0 votes
Article Rating
Subscribe
Notify of
guest

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments