Как перенести переменные из одного ЦФ ie в другой, angular - PullRequest
0 голосов
/ 28 мая 2020

Я определил здесь свойство в своей функции

evs: string
...
openArticle(url){
    this.evs = url
    console.log(this.evs)
    this.navCtrl.navigateForward('/url-page')

  }

И я пытаюсь передать значение this.evs в другой файл ts и использовать его значение, но я не знаю, как это сделать. этот. Я пробовал экспортировать его вот так.

export const webpage = this.evs

, но this.evs не имеет значения, пока кто-то не выполнит объявление функции openArticle, поэтому я продолжаю получать ошибку. «Невозможно прочитать свойство 'evs' of undefined»

Что мне нужно сделать, так это передать переменную на страницу 'url-page' и использовать значение this.evs только после того, как будет вызвана функция openArticle. Как мне go об этом?

Ответы [ 2 ]

1 голос
/ 28 мая 2020

Насколько я понимаю, вы пытаетесь обмениваться данными между двумя компонентами. Поэтому выберите один из них в соответствии с вашими требованиями.

  1. От родительского к дочернему: обмен данными через Input ().

  2. От дочернего к родительскому: совместное использование Данные через Output () и EventEmitter.

  3. Несвязанные компоненты: обмен данными со службой.

Эта ссылка будет полезна .

0 голосов
/ 28 мая 2020
  1. Если компоненты имеют отношения родитель / потомок, вы можете обмениваться данными между ними с помощью декораторов @Inpput () и @Output ().

Обмен данными от родительского к дочернему с использованием @Input ():

<h3>Parent Component</h3>

<label>Parent Component</label>c
<input type="number" [(ngModel)]='parentValue'/>

<p>Value of child component is: </p>
<app-child [value]='parentValue'></app-child>

И в дочернем компоненте 'parentValue' может быть получено как:

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {

  @Input() value: number;
  constructor() { }

  ngOnInit() {
  }

}

Теперь, в случае отправки данных от Child to Parent , мы можем использовать эмиттер событий @Output (). Таким образом, у родителя будет функция для получения переданных данных от дочернего элемента как:

parent-app.component.html 
    <app-child [value]="parentValue" (childEvent)="childEvent($event)"></app-child>

parent-app.component.ts

childEvent(event) {
console.log(event);
}

And, the child.component.ts would look like :

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {

  @Input() PData: number;
  @Output() childEvent = new EventEmitter();
  constructor() { }
  onChange(value) {
    this.childEvent.emit(value);
  }

  ngOnInit() {
  }

}
  1. Если компоненты не имеют отношения родитель / потомок, можно использовать общую службу, например SharedService который имеет BehavioralSubject, который испускает значение из любого компонента, а другой компонент может затем перехватить измененное значение.

Например:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from "rxjs/BehaviorSubject";

@Injectable()
export class SharedService {

  comp1Val: string;
  _comp1ValueBS = new BehaviorSubject<string>('');

  comp2Val: string;
  _comp2ValueBS = new BehaviorSubject<string>('');

  constructor() {
    this.comp1Val;
    this.comp2Val;

    this._comp1ValueBS.next(this.comp1Val);
    this._comp2ValueBS.next(this.comp2Val);
  }

  updateComp1Val(val) {
    this.comp1Val = val;
    this._comp1ValueBS.next(this.comp1Val);
  }

  updateComp2Val(val) {
    this.comp2Val = val;
    this._comp2ValueBS.next(this.comp2Val);
  }

И компонент1 следующим образом:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from "rxjs/BehaviorSubject";

@Injectable()
export class SharedService {

  comp1Val: string;
  _comp1ValueBS = new BehaviorSubject<string>('');

  comp2Val: string;
  _comp2ValueBS = new BehaviorSubject<string>('');

  constructor() {
    this.comp1Val;
    this.comp2Val;

    this._comp1ValueBS.next(this.comp1Val);
    this._comp2ValueBS.next(this.comp2Val);
  }

  updateComp1Val(val) {
    this.comp1Val = val;
    this._comp1ValueBS.next(this.comp1Val);
  }

  updateComp2Val(val) {
    this.comp2Val = val;
    this._comp2ValueBS.next(this.comp2Val);
  }

Компонент 2:

import { Component, AfterContentChecked } from '@angular/core';
import { SharedService } from "../../common/shared.service";

@Component({
  selector: 'app-component2',
  templateUrl: './component2.component.html',
  styleUrls: ['./component2.component.css']
})
export class Component2Component implements AfterContentChecked {

  comp1Val: string;
  comp2Val: string;

  constructor(private sharedService: SharedService) {
    this.sharedService.comp2Val = "Component 2 initial value";
  }

  ngAfterContentChecked() {
    this.comp1Val = this.sharedService.comp1Val;
  }

  addValue(str) {
    this.sharedService.updateComp2Val(str);
  }

}

Вы можете найти больше по различным типам предметов здесь

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