角度服务返回值但不在页面中显示

时间:2017-12-14 09:28:10

标签: html angular typescript

我正在从头开始学习Angular。我创建了一个名为'mylink'的组件和一个相同的服务。

我尝试使用'observable,of'和'subscribe'从服务返回一个字符串值。该服务返回字符串,但不会显示在网页中。在调试时,在组件中,它显示收到的数据是 “意外的输入结束”。控制台没有错误。我怎么解决这个问题?提前谢谢。

mylink.component.ts

import { Component, OnInit } from '@angular/core';
import { MylinkService } from '../mylink.service';
import { dashCaseToCamelCase } from '@angular/compiler/src/util';

@Component({
  selector: 'my-link',
  templateUrl: './mylink.component.html',
  styleUrls: ['./mylink.component.css']
})
export class MylinkComponent implements OnInit {
  myName: String;
  result: any;

  constructor(private mylinkService: MylinkService) { }

  ngOnInit() {
    this.getMylinkData();
  }

  getMylinkData(): void {
    this.mylinkService.getMylinkData()
    .subscribe(dataV => this.myName = dataV);
  }
}

mylink.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable()
export class MylinkService {

  private mylinkUrl = 'api/mylink';  // URL to web api

  constructor(private http: HttpClient) { }

  getMylinkData (): Observable<String> {
    var val = 'From service';
    return of(val);
  }
}

<h2>My Link page</h2>

<div>
  <label>My name is:
    <input #myName />
  </label>
</div>

2 个答案:

答案 0 :(得分:3)

试试这样:

$(document).ready(function(){
    $('section').mouseenter(function(){
        var id = $(this).attr('id');
        $('a').removeClass('colorAdded');
        $("[href=#"+id+"]").addClass('colorAdded');
    });
});

答案 1 :(得分:1)

我相信你要做的就是

   <label>My name is:
       {{myName}}
  </label>

在组件上,您将从服务返回的字符串分配给公共属性myName。如果你想在页面中显示它,你只需要插入这个值,如我的例子所示