【问题标题】:I want to image from another page我想从另一个页面图像
【发布时间】:2023-12-01 15:30:01
【问题描述】:

我是离子/角度的新手。在我的编辑个人资料页面(不同页面)中,我可以更改个人资料图片,它应该在主要个人资料页面(另一个页面)中反映相同,这两个页面是不同的。

HTML:

<ion-item lines="none">
    <ion-avatar class="ion-align-self-left" id="pic" (click)="change()">
        <img src="{{myphoto}}">
    </ion-avatar>
</ion-item>

TS:

   export class ProfilePage implements OnInit {
   myphoto:any;

  constructor(private camera: Camera) {
    this.myphoto = '/assets/img/DP.svg';
   this.statusBar.backgroundColorByHexString('#ffffff');
     }
   ngOnInit() {
  }
 take(){
     this.ishide =true;
    this.hide_input =false;
    const options: CameraOptions = {
    quality: 70,
    destinationType: this.camera.DestinationType.DATA_URL,
    encodingType: this.camera.EncodingType.JPEG,
    mediaType: this.camera.MediaType.PICTURE
    }

   this.camera.getPicture(options).then((imageData) => {
   // imageData is either a base64 encoded string or a file URI
    // If it's base64:
   this.myphoto = 'data:image/jpeg;base64,' + imageData;
   }, (err) => {
   // Handle error
   });
   }
    get() {
   this.ishide =true;
   this.hide_input =false;
    const options: CameraOptions = {
     quality: 70,
     destinationType: this.camera.DestinationType.DATA_URL,
     sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
     saveToPhotoAlbum:false
      }
      this.camera.getPicture(options).then((imageData) => {
    // imageData is either a base64 encoded string or a file URI
     // If it's base64:
     this.myphoto = 'data:image/jpeg;base64,' + imageData;
     }, (err) => {
     // Handle error
     });
      }
       }

【问题讨论】:

    标签: angular ionic-framework ionic4


    【解决方案1】:

    您可以通过“构造函数注入”导入两个模块中的相同服务

    constructor(private myProfileService: ProfileService) {  }
    

    然后只需绑定到从服务中获取其值的属性。

    【讨论】:

    • “SiddAjmera”的答案是完美的答案您创建 SharedService 来存储您的数据您将其注入您的 2 个模块构造函数的构造函数中(私有 sharedService: SharedService){} 您观察数据来自您在这些模块中的服务 ngOnInit() { this.profilePicture$ = this.sharedService.profilePicture$;在 html 中,您可以查看其中的数据 -$ 是可观察参数的命名约定 - 添加了异步管道,因为这是一个异步操作 所以请务必检查他的答案
    • 他的例子中唯一缺少的是需要在'app.module.ts'@NgModule({ providers: [ SharedService ] })提供服务
    【解决方案2】:

    您需要一些全局状态,用于存储头像图像的路径/base64。

    通常,每次启动组件(页面)时都会获取图像,并将路径/base64 分配给某个变量。

    我会使用一个全局服务或者可能是通过主题/行为主题存储化身数据的化身服务。你可以找到更多关于他们的信息here

    每当页面被初始化 (ngOnInit) 时,您都会订阅更改或从组件中的服务获取新图像。

    【讨论】:

      【解决方案3】:

      我通过简单地使用 localstorage 解决了自己的问题,并且不断返回当前页面将刷新,并且在 edit_profile 页面中所做的更改将在配置文件页面中受到影响。

      edit_profile.ts

      import { Router } from "@angular/router";
      export class ProfilePage implements OnInit {
      myphoto: any = "/assets/img/DP.svg";
      picture: any;
      
      constructor(
      private camera: Camera,
      private statusBar: StatusBar,
      private router: Router
      ) {
      this.picture = localStorage.getItem("pic");
      
      this.statusBar.backgroundColorByHexString("#ffffff");
      }
      back() {
       this.router.navigateByUrl("/profile");
        }
      take() {
      this.ishide = true;
      this.hide_input = false;
      const options: CameraOptions = {
        quality: 70,
        destinationType: this.camera.DestinationType.DATA_URL,
        encodingType: this.camera.EncodingType.JPEG,
        mediaType: this.camera.MediaType.PICTURE
      };
      
        this.camera.getPicture(options).then(
          imageData => {
          // imageData is either a base64 encoded string or a file URI
          // If it's base64:
          this.myphoto = "data:image/jpeg;base64," + imageData;
          localStorage.setItem("pic", this.myphoto);
          this.picture = localStorage.getItem("pic");
          },
           err => {
          // Handle error
         }
         );
         }
      
        get() {
       this.ishide = true;
       this.hide_input = false;
        const options: CameraOptions = {
        quality: 70,
        destinationType: this.camera.DestinationType.DATA_URL,
        sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
        saveToPhotoAlbum: false
        };
      

      edit_profile.html

      &lt;img src="{{picture}}"&gt;

      profile.ts

      export class MainProfilePage implements OnInit {
       picc: any;
      
        ionViewWillEnter() {
      this.picc = localStorage.getItem("pic");
      console.log("works");
      

      }

      profile.html

      &lt;img src="{{picc}}"&gt;

      【讨论】:

        【解决方案4】:

        创建一个SharedService。公开一个公共 Observable 和一个使用私有 BehaviorSubject 设置其值的方法:

        import { Injectable } from '@angular/core';
        import { BehaviorSubject, Observable } from 'rxjs';
        
        @Injectable()
        export class SharedService {
          private profilePicture: BehaviorSubject<string> = new BehaviorSubject<string>( 'https://firebasestorage.googleapis.com/v0/b/siddajmera-dev.appspot.com/o/Avatar.jpg?alt=media&token=ba992ea4-3198-4971-b4ee-5454ec2b3cbd');
          public profilePicture$: Observable<string> = this.profilePicture.asObservable();
        
          setProfilePicture(newProfilePicture: string) {
            this.profilePicture.next(newProfilePicture);
          }
        }
        

        在您要更改头像并设置的页面中注入此服务:

        您要显示的位置:

        import { Component } from '@angular/core';
        import { NavController } from 'ionic-angular';
        import { Observable } from 'rxjs';
        
        import { SharedService } from '../../app/shared.service';
        
        @Component({
          selector: 'page-home',
          templateUrl: 'home.html'
        })
        export class HomePage {
        
          profilePicture$: Observable<string>;
        
          constructor(
            public navCtrl: NavController,
            private sharedService: SharedService
          ) {}
        
          ngOnInit() {
            this.profilePicture$ = this.sharedService.profilePicture$;
          }
        
        }
        

        在模板中:

        <ion-header>
          <ion-navbar>
            <ion-title>Main Profile Page</ion-title>
          </ion-navbar>
        </ion-header>
        
        <ion-content padding>
          <h2>Welcome to Ionic!</h2>
          <p>
            This starter project comes with simple tabs-based layout for apps
            that are going to primarily use a Tabbed UI.
          </p>
          <p>
            Take a look at the <code>pages/</code> directory to add or change tabs,
            update any existing page or create new pages.
          </p>
          <ion-item lines="none">
                <ion-avatar class="ion-align-self-left" id="pic">
                    <img [src]="profilePicture$ | async">
            </ion-avatar>
          </ion-item>
        </ion-content>
        

        您要设置它的位置:

        import { Component } from '@angular/core';
        import { NavController } from 'ionic-angular';
        import { Observable } from 'rxjs';
        
        import { SharedService } from '../../app/shared.service';
        
        @Component({
          selector: 'page-about',
          templateUrl: 'about.html'
        })
        export class AboutPage {
        
          profilePicutre$: Observable<string>;
        
          constructor(
            public navCtrl: NavController,
            private sharedService: SharedService
          ) { }
        
          ngOnInit() {
            this.profilePicutre$ = this.sharedService.profilePicture$;
          }
        
          change() {
            this.sharedService.setProfilePicture(`https://pbs.twimg.com/profile_images/1116889337075920898/foGk0y53_400x400.jpg`);
          }
        
        }
        

        在模板中:

        <ion-header>
            <ion-navbar>
                <ion-title>
                    Edit Profile Page
                </ion-title>
            </ion-navbar>
        </ion-header>
        
        <ion-content padding>
            <ion-item lines="none">
                <ion-avatar class="ion-align-self-left" id="pic" (click)="change()">
                    <img [src]="profilePicutre$ | async">
            </ion-avatar>
          </ion-item>
        </ion-content>
        

        并在 'app.module.ts' 中提供 SharedService

        @NgModule({
            declarations: [
                HomePage,
                Aboutpage
            ],
            providers: [ SharedService ] 
        })
        

        PS:我没有使用相机 API 或示例中的任何内容。但是,即使您使用它来更新图像,这也是您的做法。使用SharedService


        这里有一个Working Sample StackBlitz 供您参考。

        【讨论】:

        • 当我尝试将您的方法集成到我的代码中时出现错误。