Значение теряется после маршрутизации в Angular5 - PullRequest
0 голосов
/ 24 мая 2018

Я пытаюсь получить значение из браузера в forms.component.ts и использовать его в student.component.ts, но я теряю значение после маршрутизации к компоненту студента, я даже пытался использовать onInit и onDestroy, чтобысохранить значение, но я не могу этого сделать.

Я добавил файл dataservice.ts для хранения значения данных в виде буфера, но значение в браузере все еще не отображается и отображается как неопределенное.

//forms.component.ts
import { Component, OnInit , OnDestroy } from '@angular/core';
import { NgForm } from '@angular/forms';
import {DataService} from '../dataservice';


@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit, OnDestroy {
   name = 'kanav';
   link = '';
    res: string;


  constructor(public dataservice: DataService) {
    this.newVal = this.res;
  }

  str: string;
  newVal: any;
  ngOnInit() {

  }
  ngOnDestroy() {
    this.dataservice.link = this.res;
    this.dataservice.test = this.name;
  }
sendValues(): void {
   this.res = this.str.substring(0, this.str.length - 11) + 'embedded=true';
   console.log(this.res);
}


}

//dataservice.ts

export class DataService {
     public link: any;
    public test: string;

}

//student.component.ts
import { Component , OnInit , OnDestroy } from '@angular/core';
// import { FormComponent } from '../form/form.component';
import {DomSanitizer} from '@angular/platform-browser';
import {DataService} from '../dataservice';

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

  constructor( public sanitizer: DomSanitizer, public dataservice: DataService) { }
    finalVal: any;
    finaltest: string;
    ngOnInit() {
         this.finalVal = this.dataservice.link ;
         this.finaltest = this.dataservice.test;
    }
    ngOnDestroy() {

    }
  show() {
    console.log(this.finaltest);
    // this.finalVal = this.forms.newVal;
    // return this.sanitizer.bypassSecurityTrustUrl(this.link);
  //     return console.log('hi there');
    return console.log();
  }

}

1 Ответ

0 голосов
/ 24 мая 2018

Вам необходимо аннотировать ваш сервис с помощью @Injectable (), в противном случае он может не быть создан при определении его в конструкторе.Или, может быть, у вас есть разные экземпляры этого в каждом компоненте

...