2
votes

I am using angular 4. when routing from one component to another component ngOninit not invoking. i have tried different methos but no use.

Here is my code:

app-router.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { GetStartedComponent } from './auth/get-started/get-started.component';
import { FbregisterComponent } from './auth/fbregister/fbregister.component';


const routes: Routes = [ 
  { path: 'GetStarted', component: GetStartedComponent, pathMatch: 'full' },
  { path: 'Fbregister', component: FbregisterComponent, pathMatch: 'full'}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

getstarted.component.ts: Here i am using facebook api

onfacebooklogin(httpobj,navobj,navthis){
    FB.Event.subscribe('auth.statusChange', (response => {
        if (response.status === 'connected') {
            FB.login(function () {          
            let accessToken = response.authResponse.accessToken;
            FB.api('/me', 'get', { access_token: accessToken, fields: 'id,name,gender,email,first_name,last_name' }, function(response) {              
                sessionStorage.setItem('fbAccessToken',accessToken);
                if (true) {

                    console.log('You are now logged in.');
                    AWS.config.update({
                        region: CognitoUtil._REGION,
                        credentials: new AWS.CognitoIdentityCredentials({
                            IdentityPoolId: CognitoUtil._IDENTITY_POOL_ID,
                            Logins: {
                                'graph.facebook.com': accessToken,                                       
                            },                          
                        })     
                    });
                    console.log("accesstoken", accessToken);
                    navthis.zone.run(() => {
                        httpobj.get('/api.json' + response.id)
                        .map( res => {
                            if (res) {
                                if (res.status === 200) {
                                    sessionStorage.setItem('faceBookLoginValid',accessToken);                              
                                    navobj.navigate(['/']);    // Here i am routing the component                            
                                } 
                            }
                        }) 
                        .catch(() =>{                      
                            sessionStorage.setItem('FacebookDetails', JSON.stringify(response));                                                        
                            navobj.navigate(['/facebookRegistration']); // Here i am routing the component
                        })
                        .subscribe((data) => {},
                        err => {});  
                    });   
                } else {
                    //console.log('There was a problem logging you in.');
                }

            });
        });
        } else {
            console.log("not connected");
        }

    }));
  }

fbregister.component.ts:

import { Component, OnInit, NgZone } from '@angular/core';
import { Http, Headers, Response, RequestOptions  } from "@angular/http";
import { Router, ActivatedRoute, Params, ParamMap,  } from '@angular/router';    

@Component({
  selector: 'app-fbregister',
  templateUrl: './fbregister.component.html',
  providers:[RegistrationFacebookUser1],
  styleUrls: ['./fbregister.component.css'],

})
export class FbregisterComponent implements OnInit {    
  public name1: string;
  public lname1: string;
  public email1: string;     
  constructor(public http:Http, private sharedService: SharedService, public registrationUser:RegistrationFacebookUser1, 
    public registrationService:RegistrationService, public router:Router, private zone:NgZone) {}

  public ngOnInit() {        
    console.log("test praba");
    var retrievedObject = sessionStorage.getItem('FacebookDetails');    
    var parsedObject = JSON.parse(retrievedObject);    
    console.log('tett',parsedObject);  
    this.email1 =  parsedObject.email; 
    this.name1 =  'test1111';        
    console.log('test',this.email1);  

  }

}

HTML

 {{name1}}<br>{{email1}}

While routing to this component ngOnint called i have tested using console but its not printed. but when i refresh the page it will load the ngOninit.

I am using sessionstorage to retrive datas. i need to display retrived datas to html while routing from one component to another component.

1
What are your routes? Are you sure you're routing to a different component, or is it only a different route parameter with the same route and therefore same component? ngOnInit is called when you navigate to a different route, but not when only a route parameter changes. - Günter Zöchbauer
@GünterZöchbauer i am using different routers only i am routing from getstarted component to fbregister component... this are my routes --> from { path: 'GetStarted', component: GetStartedComponent, pathMatch: 'full' }, to { path: 'Fbregister', component: FbregisterComponent, pathMatch: 'full'} - Prabakaran V
Please edit your question and add the code there. Code in comments is unreadable. What does "different routers" mean exactly? (different routes?) - Günter Zöchbauer
@GünterZöchbauer i have added my router code also the two components - Prabakaran V
this is strange it should , the only things that bothers me is why path match for all routes can you remove and try - Rahul Singh

1 Answers

0
votes

From the code you've shown, you're not navigating at all, that's why the OnInit is not executed.

navobj.navigate(['/']);    // Here i am routing the component

You try to navigate to "/" here, but you don't have that route defined at all. So the router does nothing, no navigation at all. Try navigating explicitly to your Facebook route there.