【发布时间】:2016-02-02 17:22:12
【问题描述】:
编辑:嗯,我应该更清楚。这是一个 angular2-meteor 项目。因为流星是反应性的,所以可能有其他方式。但是@lodewijk-bogaards 对于纯 Angular2 项目来说是一个很好的解决方案。
我正在使用 Angular 2 (TypeScript)。
我尝试使用ChatService 服务将值“12345”从App 传递给ChatDetailsComponent。
如果布尔值showChatDetails 为真,那么在我第一次单击“显示”按钮时它会显示“12345”,效果很好。
问题是,如果布尔值showChatDetails 为假,那么在我第二次单击“显示”按钮后,它将显示“12345”。我不知道为什么我第二次点击它,这应该也是第一次。
(请不要切换到[隐藏],因为我这里需要*ngIf。)
// app.ts
import {Component, View} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {ChatService} from './chat.service';
import {ChatDetailsComponent} from './chat-details.component';
@Component({
selector: 'app'
})
@View({
directives: [ChatDetailsComponent],
template: `
<button (click)="showButton()">Show</button>
<chat-details-component *ngIf="showChatDetails"></chat-details-component>
`
})
class App {
// Here if it is true, it works well. If it is false, the problem comes.
showChatDetails:boolean = false;
constructor(private _chatService: ChatService) {}
showButton() {
this._chatService.setChatId("12345");
this.showChatDetails = true;
}
}
bootstrap(App, [ChatService]);
// chat-details.component.ts
import {Component, View} from 'angular2/core';
import {ChatService} from './chat.service';
@Component({
selector: 'chat-details-component'
})
@View({
template: `
<div>ID: {{chatId}}</div>
`
})
export class ChatDetailsComponent {
chatId:string;
constructor(private _chatService: ChatService){}
ngOnInit() {
this._chatService.getChatId().subscribe(id => this.chatId = id);
}
}
// chat.service.ts
import {EventEmitter} from 'angular2/core';
export class ChatService {
chatId: EventEmitter<string> = new EventEmitter();
setChatId(id) {
this.chatId.emit(id);
}
getChatId() {
return this.chatId;
}
}
【问题讨论】:
标签: meteor typescript angular angular-meteor angular2-meteor