如何重用角度打字稿中的变量?

时间:2019-02-26 15:08:25

标签: angular typescript

我正在使用以下所示的技术开发应用程序。我有一个名为“ test.page.ts”的打字稿文件,里面有变量“ response:any”;我必须在另一个名为“ test2.page.html”的Typescript文件中重用此文件,并将其称为{{response.name}}。我该怎么做?谢谢。

我当前使用的技术:

Ionic 4.10.2
Angular 6
8.1.2 (cordova-lib@8.1.1)
TypeScript
Visual Studio Code

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);
    });
  }
}

1 个答案:

答案 0 :(得分:0)

您可以使用“主题”来执行此操作。这是一个简单的基本示例。

有效的堆叠闪电战:https://stackblitz.com/edit/angular-vts7zd?file=src%2Fapp%2Ftest.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

<span style="cursor:pointer" (click)="setLang()">Click me to change language</span>
<br><br>
<my-test></my-test>

服务

@Injectable()
export class CommonService{
  private lang$ = new Subject<string>();
  public langEvent = this.lang$.asObservable();

  public setLang(lang){
    this.lang$.next(lang);
  }
}

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();
      }
    });
  }
}

html

Current language : {{lang}}