角度模板错位

时间:2016-12-20 03:37:24

标签: angular

我正在尝试使用Angular框架实现我的应用。我目前正在使用WebSockets与服务器进行通信,到目前为止一切正常。

我创建了一个像这样的组件:

import { CountdownService, Countdown  } from './countdown.service';
import { Component } from '@angular/core';
import * as Rx from 'rxjs/Rx';

@Component({
moduleId: module.id,
selector: 'my-countdown',
templateUrl: 'countdown.component.html'
})
export class CountdownComponent {

itemName = 'Computer';

private countdown: Countdown;
constructor(private countdownService: CountdownService) {
    countdownService.countdowns.subscribe(time => {         
        this.countdown = time;
    });
}

}

所有html应该在localhost:3000中显示,所以它在之前,但现在countdown.component.html的内容已被移动到URL:

http://localhost:3000/app/countdown.component.html

我真的不知道造成这种情况的原因。我也创建了这项服务,因为它正常工作:

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs/Rx';
import {WebSocketService } from './websocket.service';

const AUCTION_URL = 'ws://localhost:9999';

export interface Countdown {
days: number,
hours: number,
minutes: number,
seconds: number
}

@Injectable()
export class CountdownService {
public countdowns: Subject<Countdown>;

constructor(wsService: WebSocketService) {
    this.countdowns = <Subject<Countdown>>wsService
        .connect(AUCTION_URL)
        .map((response: MessageEvent): Countdown => {
            let data = JSON.parse(response.data);
            return {
                days: data.days,
                hours: data.hours,
                minutes: data.minutes,
                seconds: data.seconds
            }
        });
}
}

这可能很容易解决,但我是Angular的新手,所以任何帮助都会受到赞赏。

编辑:这是主要组成部分:

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

@Component({
selector: 'my-app',
template: `
<h1>{{title}}</h1>
<my-countdown>Loading countdown ...</my-countdown>
<my-bidding>Loading bidding ...</my-bidding>
<my-bidlist>Loading bidlist ...</my-bidlist>
<my-popup></my-popup>
`
})
export class AppComponent  { 

title = 'Electronics Auction'; 

}

我的@NgModule:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';
import { BiddingComponent }  from './bidding.component';
import { CountdownComponent }  from './countdown.component';
import { BidlistComponent }  from './bidlist.component';
import { PopupComponent }  from './popup.component';

import { CountdownService }  from './countdown.service';
import { WebSocketService }  from './websocket.service';

@NgModule({
imports:      [ BrowserModule ],
declarations: [ 
  AppComponent,
  BiddingComponent,
  CountdownComponent,
  BidlistComponent,
  PopupComponent
],
providers: [CountdownService, WebSocketService],
bootstrap:    [ AppComponent ]
})
export class AppModule { }

1 个答案:

答案 0 :(得分:1)

您的组件"red"变量CountdownComponent没有设置值,因此当您使用countdown呈现模板时,这会出错,因为countdown.days订阅尚未设置{的值{1}},所以它等于未定义。

您有两种方法可以解决此问题。

组件中的选项1:

countdownService

模板中的选项2:

countdown