我试图从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();
}
}
答案 0 :(得分:0)
您需要使用@Injectable()注释您的服务,否则,在构造函数中定义它时可能无法实例化它。或者你可能在每个组件中都有不同的实例