how to update a vaiable in component.ts file from

2019-03-02 23:40发布

initially my app.component.ts file is loaded then I have two variable name and email which is updated from an API get call, in order to make this api call I need username if I dont have the username I will be not able to update this name and email.

I will be able to make the api call once i got the username but my username will be available after the login success only.

my app.html has this and the below code is a part of my sidemenu

<ion-item class="profile-info">
  <ion-icon name="person" item-left></ion-icon>
  <h2>{{name}}</h2>
  <p class="se-email">{{email}}</p>
</ion-item>

my app.component.ts file has this

name 
 email

 if(localStorage.getItem("username")){
   //here it is invoking 2nd time because i have stored the username after login so no problem
    this.getUserDetails();//this function call the same api 
  }else{
    //at first thime i am not able update the name and email because i dont have username 
    //so i am trying to update the name with set and get method where it will return my data 
    this.name =this.service.getUserName();
    this.email = this.service.getUserEmail();
  }

problem

I am not able to update the name and email variable from the home page or login page

How to update my app.component.ts file from another page like home.ts or login.ts

Update :

my complete app.html page

<ion-menu [content]="content">
  <ion-header id="slidermenu_header">
    <ion-toolbar>
      <ion-title style="padding: 0 8px 4px;">SEcure Me</ion-title>
    </ion-toolbar>
  </ion-header>

  <ion-content class="slidermenu_content">
    <ion-list style="margin: -1px 0 24px -5px;">
      <ion-item class="profile-info">
          <ion-icon name="person" item-left></ion-icon>
          <h2 >{{name}}</h2>
          <p class="se-email">{{email}}</p>
      </ion-item>
    </ion-list>
    <div id="slidermenulist">
      <ion-item *ngFor="let p of pages" (click)="openPage(p)" menuClose>
        <ion-icon [name]="p.icon" item-left></ion-icon>
          {{p.title}}
      </ion-item>
    </div>
  </ion-content>
</ion-menu>

<!-- Disable swipe-to-go-back because it's poor UX to combine STGB with side menus -->
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>

from the code above you can see I am using only one side menu in my application but if I am using this side menu on many pages

if I want to update my name and email here I have to go to my app.component.ts file like this.name="username"' andthis.email="email@gmail.com"` is working fine

In the same way if i give name and email in my home.ts file i am not able to see anything

5条回答
成全新的幸福
2楼-- · 2019-03-02 23:55

I checked your update question and here is my answer:
- First, create a function to update your varible in AppComponent:

update(){
   this.name =this.service.getUserName();
   this.email = this.service.getUserEmail();
}

- Call this function in HomePage (or what page you want) when the user is updated.
To do this, you need to go through some step:
Step1: Inject your AppComponent in HomePage:

import { Component,Inject,forwardRef } from '@angular/core';
import {AppComponent} from '../app/app.component'
@Component({
   selector: 'page-home',
   templateUrl: 'page-home.html',
   providers:[AppComponent]
})
constructor(@Inject(forwardRef(() => AppComponent)) appComponent: AppComponent){
}
login(){
   //Do the login
   //When logged in update the varible
   this.appComponent.update();
}

See detail in this answer

查看更多
一纸荒年 Trace。
3楼-- · 2019-03-02 23:57

You have to take help of Event emitters

Check out this link

https://github.com/rahulrsingh09/AngularConcepts/tree/master/src/app/parentchild

and this

https://angular.io/api/core/EventEmitter

You can also make use of Services for the Same i:e Save the info in the Service when the user is logged in and when the app component loads fetch the value from the service to display the same.

查看更多
萌系小妹纸
4楼-- · 2019-03-03 00:01

My suggestion is to create a user data provider that is a single source for all user attributes, and accessible throughout your app by injecting it into your other components.

Start by generating a provider via the Ionic CLI:

ionic generate provider user-data

Which will create a template provider for you which you can then populate with your own methods, like a getter and setter for the name and email, here is how I have done it on other projects:

import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';

@Injectable()
export class UserData {

  private name: string;
  private email: string;
  constructor(private storage: Storage) {
    this.getName().then((name) => {
      this.name = name;
    });
    this.getEmail().then((email) => {
      this.email = email;
    });
  }
  // Gets name from provider instance variable or storage if undefined.
  public getName(): Promise<string> {
    if (this.name) {
      return Promise.resolve(this.name);
    }
    else {
      return this.storage.get('name').then((name) => {
        this.name = name;
        return name;
      });
    }
  }
  // Gets email from provider instance variable or storage if undefined.
  public getEmail(): Promise<string> {
    if (this.email) {
      return Promise.resolve(this.email);
    }
    else {
      return this.storage.get('email').then((email) => {
        this.email = email;
        return email;
      });
    }
  }

  public setName(name: string): void {
    this.name = name;
    this.storage.set("name", name);
  }

  public setEmail(email: string): void {
    this.email = email;
    this.storage.set("email", email);
  }
}

Once you have defined all the methods you want in your provider next you need to import it in your app.module.ts file and add it to the providers array.

Then you can just inject the provider into the components you want to access the user data:

import { Component } from '@angular/core';
import { UserData } from '../../providers/user-data';

export class SomeComponent {

  constructor(private userData: UserData) {
    console.log(userData.getName());
    console.log(userDate.getEmail());
  }
}

This pattern is similar to that used by the official Ionic example app or Ionic Conference App which is a good point of reference.

查看更多
Melony?
5楼-- · 2019-03-03 00:05

in app.component.ts :

import { Events } from 'ionic-angular';
constructor(public events: Events) {
   events.subscribe('user:login', () => {
     this.loggedIn();
   });
}

loggedIn() {
  console.log("logged in");
}

in the calling Page:

import { Events } from 'ionic-angular';
constructor(public events: Events) {
  this.logIn();
}

logIn() {
  events.publish('user:login');
}
查看更多
虎瘦雄心在
6楼-- · 2019-03-03 00:18

In that case you have to use service and define that variable in that service and this service will accessible to throughout application.

Please have a look this reference, it may help you:https://stackoverflow.com/a/44453536/6606630

查看更多
登录 后发表回答