更新 angular 服务中的变量

updating variable in angular Service

我是 angular 的新手,正在尝试更新变量,但我的变量未在视图中更新。我正在访问在服务中创建的变量 "name" 并更新它,但它不工作。当我调用 clickme() 时,变量名称的值不会在网页上更新并显示旧值 "no name"。我想把变量名值改成"rahul"显示在页面上。

我的服务:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class FirstService {
  name:string="no name"

  setName() {
    this.name="rahul"
  }
}

代码:

import { Component, OnInit } from '@angular/core';
import { FirstServiceService } from './first-service.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [FirstService]
})
export class AppComponent implements OnInit {
  account:any
  name:string
  constructor(private userName:FirstService){      }
  ngOnInit(): void {
    this.name=this.userName.name
  }
  clickMe(e){
    this.userName.setName()
  }
}

不需要在服务中设置相同的变量名component.You可以使用任何你想要的。

在 App 组件中

clickMe(e){
    this.name=this.userName.setName();
}

服役中

getName() {
    return this.name;
}

希望对你有所帮助

你通常这样做:

服务

import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root'
})
export class FirstService {
    private name:string="no name";

    setName(_name: string): void {
        this.name = _name;
    }

    getName(): string {
        return this.name;
    }
}

组件

import { Component, OnInit } from '@angular/core';
import { FirstService } from './first-service.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [FirstService]
})
export class AppComponent implements OnInit {
  account:any
  name:string
  constructor(private firstService: FirstService){      }

  ngOnInit(): void {
    this.name=this.firstService.getName();
  }
  clickMe(e){
    this.userName.setName("rahul");
    this.name=this.firstService.getName();
  }
}

而我必须承认,name 的值通常不是通过随后从服务中使用它的相同方法设置的。不过,至少当这些是方法中仅有的两行代码时不会。但我估计你还在玩一些服务,然后没关系。

您在 OnInit 中仅将变量 "name" 等于 this.userName.name,这是因为您没有看到任何变化 - 您显示的是变量 "name",而不是变量 this.usuerName.Name.

通常你可以使用一些简单的,它是 getter 可以写在component

export class AppComponent implements OnInit {
  account:any
  //NOT have a variable "name", just a getter
  get name(){
      return this.userName.name;
  }
  //even if you want you can write
  set name(value)
  { 
      this.userName.name=value;
  }
  constructor(private userName:FirstService){      }
  ngOnInit(): void {
  }
  clickMe(e){
    this.userName.setName()
    //or this.name="George"; //if you include the function set name()
    //or this.userName.name="George"
  }
}