简体   繁体   English

component.ts 中的变量如何自动更新,而无需在 component.ts 中再次使用 updateData()/ngOnit; 何时调用 service.ts?

[英]How variables in component.ts is automatically updating without using an updateData()/ngOnit again in component.ts ; when a service.ts is called?

I am new to Angular.我是 Angular 的新手。 While implementing a function using service class in my component class, i got this logic issue.在我的组件 class 中使用服务 class 实现 function 时,我遇到了这个逻辑问题。 Below is the code-下面是代码-

Stackblitz link Stackblitz链接

app.module.ts app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    AddUserComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts app.component.ts

import { UserService } from './services/user.service';
import {  Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [UserService]
})
export class AppComponent implements OnInit {
  title = 'UserAvailabe';

  constructor(private userService: UserService) {
  }

  pusers: { name: string; status: string; }[] = [];

  ngOnInit() {
    this.pusers = this.userService.users;
    console.log("ngOnInit called");
  }    
}

app.component.html app.component.html

<div class="container">
  <app-add-user></app-add-user>
  <div class="user-div" *ngFor="let user of pusers">
    <div class="user-name">{{user.name}}</div>
    <div class="user-status">{{user.status}}</div>
  </div>
</div>

add-user.component.ts添加用户.component.ts

import { UserService } from './../services/user.service';
import { Component, OnInit } from '@angular/core';

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

  username: string = '';
  status: string = 'active';

  constructor(private userService: UserService) { }

  ngOnInit(): void {
  }

  addUser() {
    this.userService.addNewUser(this.username, this.status);
    console.log("addUser() called");
    console.log(this.userService.users);
  }

}

add-user.component.html add-user.component.html

<div class="form">
    <div class="uName">
        <input type="text" placeholder="Username" id="username" [(ngModel)]="username">
    </div>
    <div class="uStatus">
        <select name="status" id="status" [(ngModel)]="status">
            <option value="active">active</option>
            <option value="inactive">inactive</option>
        </select>
    </div>
    <div class="cUser">
        <button (click)="addUser()">Create User</button>
    </div>
</div>

user.service.ts用户服务.ts

export class UserService {

  constructor() { }

  users = [
    { name: 'John', status: 'active' },
    { name: 'Mark', status: 'inactive' },
    { name: 'Steve', status: 'active' }
  ]

  addNewUser(pname: string, pstatus: string) {
    this.users.push({ name: pname, status: pstatus });
  }
}

So, Initally using ngOnint() , pusers in app.component.ts get populated from service class.因此,最初使用ngOnint()pusers中的app.component.ts从服务 class 中填充。 But when I add a new username and its status, the users in app.service.ts gets updated using addUser() .但是当我添加一个新的用户名及其状态时, app.service.ts中的users会使用addUser()进行更新。 But how it is again updating the pusers in app.component.ts without calling the ngOnint() again / any other updateData() methods while running?但是它如何再次更新pusers中的app.component.ts而无需在运行时再次调用ngOnint() /任何其他 updateData() 方法?

PS: Please forgive if my question is wrong. PS:如果我的问题是错误的,请原谅。 Thanks a lot for your help:)非常感谢你的帮助:)

In javascript arrays and objects are passed by reference, not by value.在 javascript arrays 中,对象通过引用而不是值传递。 Thus pusers is just referencing the memory location of users.因此 pusers 只是引用用户的 memory 位置。 To learn more read:要了解更多信息,请阅读:

https://medium.com/nodesimplified/javascript-pass-by-value-and-pass-by-reference-in-javascript-fcf10305aa9c#:~:text=In%20Javascript%20objects%20and%20arrays%20follows%20pass%20by%20reference.&text=so%20if%20we%20are%20passing,of%20the%20object%20can%20change . https://medium.com/nodesimplified/javascript-pass-by-value-and-pass-by-reference-in-javascript-fcf10305aa9c#:~:text=In%20Javascript%20objects%20and%20arrays%20follows%20pass %20by%20reference.&text=so%20if%20we%20are%20passing,of%20the%20object%20can%20change

If you want to copy the value of an array instead of its reference, in ngOnInit you can just write:如果你想复制一个数组的值而不是它的引用,在 ngOnInit 你可以写:

this.pusers = [...this.userService.users];

and this will fix your problem这将解决您的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 service.ts 会在 component.ts 之前执行吗? - Does service.ts get executed before component.ts? 如何从 service.ts 文件中的 Component.ts 文件调用 function,该文件在 angular 的同一组件中 - How to Call function from Component.ts file in service.ts file which is in the same component in angular 如何将 component.ts 中的变量发送到 service.ts 进行身份验证 Angular - How to send variable in component.ts to service.ts for authentication Angular 如何绑定选择/选项值以在service.ts中而不是component.ts中获得请求功能(角度8) - How to bind selected/option value to get request function in service.ts and not component.ts (Angular 8) 如何在发射成功时处理从 service.ts 到 component.ts 的 socket.io 确认 Angular 8 - How to handle socket.io acknowledgement from service.ts to component.ts on emit success Angular 8 订阅值在component.ts中返回undefined但在service.ts中存在值 - subscribed value returns undefined in component.ts but value exists in service.ts 我的service.ts不会将数据返回到component.ts - My service.ts doesn't return data to component.ts Component.ts上的Angular 4 forEach() - Angular 4 forEach() on component.ts 在 component.ts 上刷新路由器 - Refresh router on component.ts 在component.ts中使用Pipe - Using Pipe inside the component.ts
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM