使用订阅或承诺调用JSON

时间:2018-10-24 14:07:19

标签: json angular6 primeng

如果我使用promise函数,则会收到错误消息:

  

**类型“对象”上不存在属性“ TEST” **   我的ServiceClass

使用方法:

  getTEST() {
   return this.http.get(this.configUrl)
    .toPromise()
    .then(res => <Tariftabelle[]> res.TEST)
    .then(data => { return data; });
  }

还有我的json-Date:

{
     "TEST": [
      {"leistung": "hello", "sb": "World"},
      {"leistung": "hellooo", "sb": "Test-Wordl"}
      ],
      "TEST2": [
      {"leistung": "hola", "basic": "1", "premium": "2", "exzellent": "3"},
      {"leistung": "hola two", "basic": "2", "premium": "4", "exzellent": "6"},
      {"leistung": "hola three", "basic": "4", "premium": "7", "exzellent": "9"}
    ]
}

或者iIuse如何在没有承诺的情况下进行订阅?

1 个答案:

答案 0 :(得分:0)

服务

@Injectable({
  providedIn: 'root'
})
export class MyService {

    getTEST(): Observable<any> {
       return this.http.get(this.configUrl);   
    }

}

组件

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.html',
  styleUrls: ['./my-component.scss']
})
export class MyComponent implements OnInit {

    data: any;

    constructor(private myServ: MyService) {}

    ngOnInit() {
        this.myServ.getTEST().subscribe(res => {
            this.data = res;
        });
    }
}

模板

<pre>{{ data | json }}</pre>

正如您在组件的初始化中看到的那样,您订阅了服务getTEST请求。在订阅中,当您收到json数据时,便将它们分配给本地data变量。现在,您可以将其访问到模板中。