如何使用Angular将页面属性导入数据服务



我想在我的Ionic应用程序中将trackingId从tracking.page.ts导入到geolocation.service.ts。有人知道如何使用Angular和TypeScript吗?

下面您可以看到代码的摘录。

跟踪.page.ts

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { GeolocationService } from '../../app/geolocation.service';
import { UserService } from '../../app/user.service';
import { Insomnia } from '@ionic-native/insomnia/ngx';
import { LoadingController } from '@ionic/angular';
import { AlertController } from '@ionic/angular';
import { AppComponent } from '../app.component';
import { Storage } from '@ionic/storage';
declare var google;
@Component({
selector: 'app-tracking',
templateUrl: './tracking.page.html',
styleUrls: ['./tracking.page.scss'],
})
export class TrackingPage implements OnInit {
@ViewChild('map', { static: true }) mapElement: ElementRef;
map: any;
markers = [];
geoLocations: any;
watchLocationUpdates: any;
isWatching: boolean;
interval: any;
geoLatitude: number;
geoLongitude: number;
geoAccuracy: number;
timeStamp: any;
uId: string;
trackingId: string; // This is the trackingId
...

地理定位服务.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../environments/environment';
@Injectable({
providedIn: 'root'
})
export class GeolocationService {
databaseUrl = environment.firebase.databaseURL;
constructor(private http: HttpClient
) {
console.log('Hello GeolocationService Provider');
console.log('GeolocationService: ', this.databaseUrl);
}
...

您可以创建一个服务,将trackingid保存在其中,然后将其注入第二个页面。

尝试在服务之外执行此操作将遇到分区和更改检测问题。

使用等可观察主题在服务文件中定义trackingid

public trackingid: BehaviorSubject<number> = new BehaviorSubject(1);

然后在服务中设置它,并像下面一样获取它

public getTrackingId(): boolean {
return this.trackingid.value;
}

public setTrackingId(){
return this.trackingid.next(2);
}

现在,您可以从组件中获取并设置为trackingId。

最新更新