为什么我的Angular应用程序在传递新属性值时没有更改标题?

时间:2017-12-09 17:39:10

标签: angular angular2-services angular-services

我现在正在学习Angular 2,对我来说这似乎很复杂,所以如果我的问题很愚蠢,我会道歉。

我想使用服务在类之间传递值,并在每次更改此值时更新标题。我成功传递了代码,但它没有更新它。我想这是因为在.subscribe()函数中调用ngOnInit,但如果我想动态更新标题,我不知道如何更改它。这是我的代码:

app.component.ts

import { Component, OnInit } from '@angular/core';
import { Spot } from './spot';
import { SpotListComponent } from './spot-list/spot-list.component';
import { DataService } from './data.service';

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

  constructor(public src: DataService){}
  ngOnInit(){
    //this.title = this.src.getTitle();
    this.src.getTitle().subscribe((newTitle: string) => { this.title = newTitle });
  }
}

data.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';

@Injectable()
export class DataService {

    newTitle: string = 'anyád';

    constructor(){}

    getTitle(): Observable<string> {
        return of(this.newTitle);
    }

    changeTitle(toThis: string){
        this.newTitle = toThis;
        console.log('title changed to this: ' + toThis);
        console.log('new title property value is: ' + this.newTitle);
    }

}

斑点list.component.ts

import { Component } from '@angular/core';
import { Spot } from '../spot';
import { SpotList } from '../spot-list/spot-list';
import { DataService } from '../data.service';

@Component({
  selector: 'app-spot-list',
  templateUrl: './spot-list.component.html',
  styleUrls: ['./spot-list.component.css']
})
export class SpotListComponent {

    spotlist = SpotList;
    selectedSpot: Spot;

    constructor(public src: DataService){}

    edit(spot: Spot): void {
        //this.selectedSpot = spot;
        console.log(spot);
    }

    del(): void {
        console.log('deleted');
        this.src.changeTitle('köcsög');
    }
}

点焊list.component.html

...
<td class="fa fa-trash" (click)="del()"></td>
...

0 个答案:

没有答案