简体   繁体   English

Angular2双重绑定未更新

[英]Angular2 double binding not updated

banner html template 横幅html模板

 body: {{body}}
    <br>
    message: {{message}}

    <button type="submit" (click)="updateMessage('haha')">Update Message</button>

banner component 标语组件

import { Component } from '@angular/core';
import { StateService } from 'app/common/state.service';

@Component({
    selector:       'banner',
    templateUrl:    'app/banner/banner.component.html',
    providers: [StateService]
})
export class BannerComponent {
    body:           string = 'This is the about home body';
    message:        string;

    constructor(private stateService: StateService) {

    }

    ngOnInit() {
        this.message = this.stateService.getMessage();
    }

    updateMessage(m: string): void {
        this.stateService.setMessage(m);
    }
}

state service 国家服务

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

@Injectable()
export class StateService {
    private message = 'Hello Message';
    getMessage(): string {
        return this.message;
    };
    setMessage(newMessage: string): void {
        console.error('setting message' + newMessage);
        this.message = newMessage;
    };
}

I'm following some tutorials on angular 2 and I'm trying to have one shared service (common state) which has a property which you can set from a component (banner). 我正在关注有关angular 2的一些教程,并且尝试拥有一个共享服务(公共状态),该共享服务具有可以从组件(横幅)设置的属性。

Everything is compiling and the setter inside the state service is fired with the correct value. 一切都在编译中,并且使用正确的值触发了状态服务中的设置器。 Only is the double binding (message: {{message}}) inside banner.component.html not updated. 只更新banner.component.html中的双重绑定(消息:{{message}})。 How come this is not the case? 事实并非如此吗?

This way it doesn't work. 这样就行不通了。 To work it this way you have to use Observable but that's a different story. 要以这种方式工作,您必须使用Observable,但这是另一回事。

Here, What you can do is, 在这里,您可以做的是

{{stateService.getMessage()}}   //<<<====use getMessage() in template as shown here.

export class BannerComponent {
    body:           string = 'This is the about home body';
    message:        string;

    constructor(private stateService: StateService) {}
______________________________________________________
    /*          not required anymore
    ngOnInit() {
        this.message = this.stateService.getMessage();
    }
    */
_______________________________________________________
    updateMessage(m: string): void {
        this.stateService.setMessage(m);
    }
}

Or you can just write getter like: 或者您可以像这样写getter:

get message(): string {
  return this.stateService.getMessage();
}

and you won't need to change the html: 而且您无需更改html:

message: {{message}}

There are also another ways to do that. 还有另一种方法可以做到这一点。 For example is use object instead of string. 例如,使用对象而不是字符串。 Strings are immutable 字符串是不可变的

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM