[英]How can I reuse a variable in angular typescript?
I'm developing an application with the technologies shown below. 我正在使用以下技术开发应用程序。 I have a Typescript file called "test.page.ts", inside there is the variable "response: any";
我有一个名为“ test.page.ts”的打字稿文件,里面有变量“ response:any”; I have to reuse this in another Typescript file called "test2.page.html", calling it that, {{response.name}}.
我必须在另一个名为“ test2.page.html”的Typescript文件中重用此文件,并将其称为{{response.name}}。 How can I do it?
我该怎么做? Thank you.
谢谢。
Technologies that I currently use: 我目前使用的技术:
Ionic 4.10.2
Angular 6
8.1.2 (cordova-lib@8.1.1)
TypeScript
Visual Studio Code
test.page.ts test.page.ts
import { Component, OnInit } from '@angular/core'; import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; import { LoadingController, NavController, MenuController } from '@ionic/angular'; @Component({ selector: 'app-test', templateUrl: './test.page.html', styleUrls: ['./test.page.scss'], }) export class TestPage implements OnInit { response: any; searchTerm: any = ''; constructor(private http: HttpClient, private loadingCtrl: LoadingController, private navCtrl: NavController) { this.getData(); } ngOnInit() { } getData() { this.http.get('URL') .subscribe((response) => { this.response = response; console.log(this.response); }); } }
You can use Subject to do that. 您可以使用Subject来做到这一点。 Here's a simple, basic example.
这是一个简单的基本示例。
Working stackblitz: https://stackblitz.com/edit/angular-vts7zd?file=src%2Fapp%2Ftest.component.ts 可工作的stackblitz: https ://stackblitz.com/edit/angular-vts7zd ? file = src%2Fapp%2Ftest.component.ts
App.Component.ts App.Component.ts
export class AppComponent {
isEnglish = true;
constructor(private service: CommonService){ }
setLang(){
this.isEnglish = !this.isEnglish;
(this.isEnglish) ? this.service.setLang('IT') : this.service.setLang('EN');
}
}
App.component.html App.component.html
<span style="cursor:pointer" (click)="setLang()">Click me to change language</span>
<br><br>
<my-test></my-test>
The service 服务
@Injectable()
export class CommonService{
private lang$ = new Subject<string>();
public langEvent = this.lang$.asObservable();
public setLang(lang){
this.lang$.next(lang);
}
}
Test.Component.ts (it handles the data received from the subscription) Test.Component.ts(它处理从订阅接收的数据)
export class TestComponent implements OnInit {
lang ="default";
constructor(private service: CommonService, private cdr: ChangeDetectorRef) {}
ngOnInit(){
this.service.langEvent
.subscribe(res => {
if(!!res){
this.lang = res;
this.cdr.detectChanges();
}
});
}
}
The html HTML
Current language : {{lang}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.