Не удается вызвать функцию в многостраничном приложении Ionic 4 - PullRequest
0 голосов
/ 05 ноября 2019

Я пытаюсь заставить функцию работать для многостраничного приложения Ionic 4.

Функция хранится в файле profile.page.ts и должна представлять информацию о пользователе из базы данных Firebase. Подключение к БД работает нормально. Мне кажется, я просто неправильно вызвал функцию.

profile.page.ts

import { Component, OnInit } from '@angular/core';
import { AuthenticateService } from '../authentication.service';
import { DataServiceService } from '../../app/data-service.service';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.page.html',
  styleUrls: ['./profile.page.scss'],
})
export class ProfilePage implements OnInit {
  userEmail: string;
  userOrganization: any;
  organizations: any = [];
  displayUserName: any;

  constructor(
      private authService: AuthenticateService,
      public dataService: DataServiceService) {
      console.log(`Profile Page called`);
      }

  ngOnInit() {
  }

  initProfileData() {
    if (this.authService.userDetails()) {
      this.userEmail = this.authService.userDetails().email;
      console.log('initProfileData ', this.userEmail, this);
    }

    this.dataService.getUserOrganization()
      .subscribe((response) => {
        this.userOrganization = response;
        console.log('userOrganization ', response);

        const result = this.organizations.find((obj: { organizationId: Object; }) => {
          return obj.organizationId === response;
        });
        console.log('obj.organizationId ', response);
      });

    this.dataService.fetchUserName()
      .subscribe((response) => {
        this.displayUserName = response;
        console.log('fetchUserName ', response);
      });

  }

}


profile.page.html

<ion-header>
  <ion-toolbar>
    <ion-title>Profile</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>
        <div>
        <h5>Profile</h5>
        <ion-card >
          <ion-card-content>
            <div><b>User Name:</b> {{ displayUserName }}</div>
            <p></p>
            <div><b>Email:</b> {{ userEmail }}</div>
            <p></p>
            <div><b>Organization:</b> {{ userOrganization }}</div>
          </ion-card-content>
        </ion-card>
        <ion-button color="danger" expand="block" (click)="logout()">
          Log Out
        </ion-button>
      </div>
</ion-content>


data-service. service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment  } from '../environments/environment';
// import * as firebase from 'firebase/app';


@Injectable({
  providedIn: 'root'
})
export class DataServiceService {
  userId: any;
  userName: any;
  userOrganization: any;
  products: any;
  databaseUrl = environment.firebase.databaseURL;

  constructor(private http: HttpClient) {
    console.log('Hello DataServiceService Provider');
    console.log(this.databaseUrl);
    this.userId = localStorage.getItem('userId');
    console.log('userId ', this.userId);
  }

  getOrganizations() {
    return this.http.get(`${this.databaseUrl}/organizations/.json`);
  }

  setUserId(userId: string) {
    console.log('setUserId ', this.userId);
    this.userId = userId;
    localStorage.setItem('userId', userId);
  }

  getUserId() {
    return this.userId;
  }

  getUserName() {
    return this.userName;
  }

  setUserName(userName: string) {
    this.userName = userName;
  }

  getProducts() {
    return this.http.get(`${this.databaseUrl}/products/.json`);
  }

  insertUser(data: { uId: any; }) {
    return this.http.put(`${this.databaseUrl}/users/${data.uId}.json`, data);
  }

  getUserOrganization() {
    return this.http.get(`${this.databaseUrl}/users/${this.userId}/organization.json`);
  }

  // an API to insert product views with firebase generated key
  insertProductViewAnalaytics(data: any) {
    return this.http.post(`${this.databaseUrl}/users/${this.userId}/product_views.json`, data);
  }

  getProductViewsForUser() {
    return this.http.get(`${this.databaseUrl}/users/${this.userId}/product_views/.json`);
  }

  fetchUserName() {
    return this.http.get(`${this.databaseUrl}/users/${this.userId}/userName/.json`);
  }

  // an API to insert product views with custom timestamp based key
  insertProductViewAnalyticsTimestamp(data: { scannedAt: any; }) {
    // tslint:disable-next-line: max-line-length
    return this.http.put(`${this.databaseUrl}/product_views_timestamp/${data.scannedAt}.json`, data);
  }

}


Информация из БД должна отображаться на странице HTML.

1 Ответ

1 голос
/ 05 ноября 2019

Вы должны добавить это на profile.page.ts

ngOnInit() {
  this.initProfileData()
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...