繁体   English   中英

“可观察”类型上不存在属性“json”<any> '</any>

[英]Property 'json' does not exist on type 'Observable<any>'

我正在尝试学习 angular 但是在尝试将响应中的值放入局部变量时我被卡住了。

我来自服务器的数据看起来像:

[{text : 'Some text', owner: 'Tim'}, {text : 'second Message', owner : 'Jane'}]

这是我的服务:

import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs';

@Injectable()
export class WebService {

    constructor(private http: Http) {}

    getMessages():Observable<any> {
        return this.http.get('http://localhost:1234/messages');
    }
}

这是我的组件:

import { Component } from '@angular/core'
import { WebService } from './web.service'

@Component({
    selector: 'messages',
    template: `
    <div *ngFor="let message of messages">
        <mat-card style="margin:8px">
            <mat-card-title>{{message.owner}}</mat-card-title>
            <mat-card-content>{{message.text}}</mat-card-content>
        </mat-card>
    </div>
    `
})
export class MessagesComponent {
    constructor(private webService : WebService) {}

    async ngOnInit() {
        var response = await this.webService.getMessages();
        this.messages = response.json();
    }

    messages = [];
}

我尝试了其他几种方法,例如 map 并订阅,但它们似乎都不起作用。 我已经尝试了几乎所有来自互联网的示例,但总是遇到问题。 请有人解释一下。

async / await 不与 observables 混合。 rxjs 用法如下:

ngOnInit() {
    this.webService.getMessages().subscribe(response => {
      this.messages = response.json();
    })
}

使用最佳实践将 observable 暴露给模板,并让 Angular 使用异步 pipe 在幕后处理订阅/取消订阅。

import { Component } from '@angular/core'
import { WebService } from './web.service'
import { Observable } from 'rxjs';

@Component({
    selector: 'messages',
    template: `
    <div *ngFor="let message of messages$ | async">
        <mat-card style="margin:8px">
            <mat-card-title>{{message.owner}}</mat-card-title>
            <mat-card-content>{{message.text}}</mat-card-content>
        </mat-card>
    </div>
    `
})
export class MessagesComponent {

   messages$: Observable<any>;

   constructor(private webService : WebService) {}

   ngOnInit() {
        this.messages$ = this.webService.getMessages();
    }
}

接受上述建议也在您的服务中执行此操作

import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs';

@Injectable()
export class WebService {

    constructor(private http: Http) {}

    getMessages():Observable<any> {
        return this.http.get('http://localhost:1234/messages').pipe(
            map(x => x.json())
        );
    }
}

暂无
暂无

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

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